Model validation with Scope on Ruby on Rails

Asked

Viewed 520 times

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 an attribute of C to be unique in the scope of B 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 him to be unique in the scope of A, when I don’t have a_id in table C?

1 answer

1


To do it that way, you really would need to create the column a_id on the table C.

Thus, in addition to you can use the predefined validation of :uniqueness, you can create a unique key restriction in the bank, which is fundamental to ensure uniqueness in case of competing accesses. To do this, add to Migration:

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

To set the value of a_id in 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 alternative solution would be to use a custom validation.

  • I will have to create more columns of references anyway, otherwise it would be very complex. In my case, in fact, I have up to 3 models cascateados. Was worth the force. =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.