cai*_*nne 3 ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1
使用包含嵌套模型属性的表单编辑模型时,似乎只有在子对象上至少有一个字段发生更改时才会验证子对象.
但是,假设您的验证规则已更改,以便正在编辑的一个或多个嵌套模型不再被视为有效.如何强制Rails重新验证所有嵌套模型的所有字段?
UPDATE
这是一个完全有效的黑客行为.我希望有人知道更优雅的方法.
# 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
Run Code Online (Sandbox Code Playgroud)
对此的答案变得相当简单.在父模型上,您只需显式声明您希望验证关联的子项.
# parent.rb
validates_associated :children
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1890 次 |
最近记录: |