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

查看:18
本文介绍了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?

提前致谢

--黛布

推荐答案

您可以使用:

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天全站免登陆