When you edit a model with a form that contains nested model attributes, it seems as if the child objects are only validated if at least one field on the child object has changed.
However, suppose that your validation rules have changed, such that one or more of the nested models being edited are no longer considered valid. How can you force Rails to re-validate the all fields for all of the nested models?
UPDATE
Here's a total hack that works. I hope somebody knows a more elegant approach.
# parent.rb
has_many :children
# Manually force validation of all the children.
# This is lame because if you have multiple child associations, you'll have to
# keep updating this method.
def reset_validation
self.children.each{|child| child.valid? }
self.valid?
end
# parent_controller.rb
def update
@parent.reset_validation
if @parent.update_attributes(params[:parent])
redirect_to(root_path, :notice => 'Parent successfully updated.')
else
render :action => "edit"
end
end
The answer to this turned out to be rather simple. On the parent model, you simply explicitly declare that you want the associated children validated.
# parent.rb
validates_associated :children
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With