Validating a template with scope in Ruby on Rails

1

Suppose the models:

class A < ActiveRecord::Base
  has_many :bs
end

class B < ActiveRecord::Base
  belongs_to :a
  has_many :cs
end

class C < ActiveRecord::Base
  belongs_to :b
end

If I want a C attribute to be unique in B's scope I can do this:

class C < ActiveRecord::Base
  belongs_to :b
  validates :atributo, presence: true,
                       uniqueness: { case_sensitive: false,
                                     scope: :b_id,
                                     message: 'precisa ser único' }
end

But how do I want it to be unique in the scope of A, since I do not have a_id in table C?

    
asked by anonymous 12.05.2014 / 14:27

1 answer

1

To do this, it would really be necessary to create the a_id column in the C table.

So, in addition to using predefined validation of :uniqueness , you can create a unique key constraint on the database, which is fundamental to ensure uniqueness in case of concurrent access. To do this, add no migration:

    add_index :cs, [:a_id, :atributo], unique: true

To set the value of a_id to C , I suggest creating a callback before_validation :

    before_validation :set_a_id
    def set_a_id
      self.a_id = b.a_id
    end

The workaround would be to use custom validation .

    
13.05.2014 / 14:27