错误被添加到记录的错误对象中,但仍保存关联。
class Parent < ActiveRecord::Base
validate :valid_child?
#validation methods
protected
def valid_child?
@child_names = Hash.new
self.children.each do |curr_child|
if @child_names[curr_child.name].nil?
@child_names[curr_child.name] = curr_child.name
else
errors.add(:base, "child name should be unique for children associated to the parent")
end
end
end
#associations
has_and_belongs_to_many :children, :join_table => 'map__parents__children'
end
#query on rails console
@parent = Parent.find(1)
@parent.children_ids = [1, 2]
@parent.save
答案 0 :(得分:3)
问题在于,对于现有记录,@parent.children_ids = [1, 2]
将在调用@parent.save
之前对数据库进行更改。
尝试使用validates_associated验证孩子,而不是滚动自己的验证。
要确保子项的名称在父项的上下文中是唯一的,请使用validates_uniqueness_of和:scope
选项来确定父ID的唯一性。类似的东西:
class Child < ActiveRecord::Base
belongs_to :parent
validates_uniqueness_of :name, :scope => :parent
end