Rails:如何要求至少一个字段不为空 [英] Rails: how to require at least one field not to be blank

查看:125
本文介绍了Rails:如何要求至少一个字段不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以通过将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_atupdated_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:如何要求至少一个字段不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆