Tuesday, 2 September 2014

Validating uniqueness of nested model with parent_id

I recently came across to an interesting issue where I setup a uniqueness validator on a field, with a scope on the parent's Id. And Thought that is should work for me, This was fine for updating with an existing parent, but if I ever created two or more new fields, the validation would fail because there was no ID on the parent model yet for the child to validate against.

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

class Parent < ActiveRecord::Base 
  has_many :children 
  accepted_nested_attributes_for :children 
end

Here is the code snippet that will solve the issue and allow you to validate uniqueness of nested model on create as well as on update.

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

class Parent < ActiveRecord::Base 
    has_many :children 
    accepted_nested_attributes_for :children   
    validate :uniqueness_of_children 

private   

  def uniqueness_of_children 
    hash = {} 
    children.each do |child|
      if hash[child.value]
        errors.add(:"text", "error") if errors[:"text"].blank? 
        child.errors.add(:value, "has already been taken") 
      end
      hash[child.value] = true 
    end 
  end

end

No comments:

Post a comment