Reputation: 4003
suppose I have models
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
end
I have an attribute for child call it serial_no. I want to add a validation so that every children has a unique serial no under a parent how can I add this validation?
Upvotes: 0
Views: 43
Reputation: 1230
Use scoped validation:
class Child < ActiveRecord::Base
belongs_to :parent
validates :serial_no, :uniqueness => {:scope => :parent_id}
end
Upvotes: 2