问题描述
我知道我可以通过将validates_presence_of :field
添加到模型中来要求输入一个字段.但是,我如何要求至少一个字段为必填字段,而不要求任何特定字段?
I know I can require a field by adding validates_presence_of :field
to the model. However, how do I require at least one field to be mandatory, while not requiring any particular field?
预先感谢
-Deb
推荐答案
您可以使用:
validate :any_present?
def any_present?
if %w(field1 field2 field3).all?{|attr| self[attr].blank?}
errors.add :base, "Error message"
end
end
根据评论从Rails 3+的原始答案更新.
updated from original answer for Rails 3+ as per comment.
但是您必须手动提供字段名称.您可以使用Model.content_columns.map(&:name)
获取模型的所有内容列,但是它还将包含created_at
和updated_at
列,而这可能并不是您想要的.
But you have to provide field names manually.You could get all content columns of a model with Model.content_columns.map(&:name)
, but it will include created_at
and updated_at
columns too, and that is probably not what you want.
这篇关于Rails:如何要求至少一个字段不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!