开发者

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

开发者 https://www.devze.com 2023-04-06 16:57 出处:网络
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.

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开发者_如何学JAVA 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号