跳过 Rails 3 中嵌套属性的验证? [英] Skip validations for nested attributes in Rails 3?
问题描述
我目前正在使用嵌套的 forms/fields_for,我想知道是否有一种简单的方法可以跳过对嵌套属性的验证?
I'm currently working with nested forms/fields_for and I was wondering if there was an easy way to skip validations for nested attributes?
我可以在某处挤一个 object.nested_object.save(:validate => false) 吗?
Can I maybe squeeze a object.nested_object.save(:validate => false) in somewhere?
推荐答案
您只需要将保存分为两部分.第一部分关于父保存,第二部分关于嵌套
You just need do your save in two part. The first save about the parent saving and second part about nested
如果您在此嵌套字段上使用 accepts_nested_attributes_for
If you use an accepts_nested_attributes_for
on this nested field
def create
nested_params = params[:object].delete(:nested_attributes)
if object = Object.create(params[:object]) &&
object.update_attributes(nested_params, :validate => false)
redirect_to object_url(object)
else
render :new
end
end
根据 Cojones 的评论更新:
如果你不使用这个选项,你需要直接分配nested_attribute,比如注释上的解释:
If you don't use this option you need assign directly the nested_attribute like explain on comment :
def create
nested_params = params[:object].delete(:nested_attributes)
if object = Object.create(params[:object]) &&
object.nested_object.update_attributes(nested_params, :validate => false)
redirect_to object_url(object)
else
render :new
end
end
请查看评论以获取更多信息.
Please see comment for more information.
这篇关于跳过 Rails 3 中嵌套属性的验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!