rails has_many 最小集合大小更新验证 [英] rails has_many minimum collection size update validation
本文介绍了rails has_many 最小集合大小更新验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个接受嵌套属性的 has_many
关联.我需要集合中至少有 1 个关联对象,因此我编写了一个自定义验证器:
I have a has_many
association that accepts nested attributes. I need for there to be a minimum of 1 associated object in the collection, so I wrote a custom validator:
class MinimumCollectionSizeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if value.size < options[:size]
record.errors[attribute] << (options[:message] || "must have at least #{options[:size]} line.")
end
end
end
模型看起来像:
has_many :foos, :dependent=>:destroy
accepts_nested_attributes_for :foos
validates :foos, :minimum_collection_size=>{:size=>1}
这在模型创建上效果很好,但在更新时失败了.@my_model.update_attributes(params[:my_model])
返回 true,即使 _destroy 删除了所有 foos.
This works great on model creation, but fails miserable on update. @my_model.update_attributes(params[:my_model])
returns true even if all the foos are removed by _destroy.
如何让 update_attributes
的行为与 save
相同?
How do I get update_attributes
to behave the same as save
?
推荐答案
验证集合最小大小的更好方法:
A better way to validate the minimum size of a collection:
validates :my_association, :length => { :minimum => Fixnum}
这篇关于rails has_many 最小集合大小更新验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文