Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you force validation of all fields of nested models, even if they have not changed? (Rails 3.1)

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
like image 586
cailinanne Avatar asked Jan 19 '26 14:01

cailinanne


1 Answers

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
like image 150
cailinanne Avatar answered Jan 21 '26 06:01

cailinanne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!