ActiveRecord Validation: association saved even if validation failed
Errors are added to error object of record but associations are still saved.
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开发者_如何学JAVA_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
The problem is that, for an existing record, @parent.children_ids = [1, 2]
will take effect a change in the database before the call to @parent.save
.
Try using validates_associated to validate the children rather than rolling your own validation.
To make sure that the children's names are unique within the context of the parent, use validates_uniqueness_of with the :scope
option to scope the uniqueness to the parent id. Something like:
class Child < ActiveRecord::Base
belongs_to :parent
validates_uniqueness_of :name, :scope => :parent
end
精彩评论