【发布时间】:2011-09-21 16:05:55
【问题描述】:
当您使用包含嵌套模型属性的表单编辑模型时,似乎只有在子对象上的至少一个字段发生更改时才验证子对象。
但是,假设您的验证规则已更改,因此正在编辑的一个或多个嵌套模型不再被视为有效。如何强制 Rails 重新验证所有嵌套模型的所有字段?
更新
这是一个完全有效的技巧。我希望有人知道更优雅的方法。
# 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
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1