Asnad Atta
Asnad Atta

Reputation: 4003

unique serial no of child record under each parent record

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

Answers (1)

Felix Borzik
Felix Borzik

Reputation: 1230

Use scoped validation:

class Child < ActiveRecord::Base
  belongs_to :parent
  validates :serial_no, :uniqueness => {:scope => :parent_id}
end

Upvotes: 2

Related Questions