Rails: how to require at least one field not to be blank

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

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?

thanks in advance

-- Deb

回答1:

You can use:

validate :any_present?  def any_present?   if %w(field1 field2 field3).all?{|attr| self[attr].blank?}     errors.add :base, "Error message"   end end 

EDIT: updated from original answer for Rails 3+ as per comment.

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.



回答2:

Add a validate method to your model:

def validate   if field1.blank? and field2.blank? and field3.blank? # ...     errors.add_to_base("You must fill in at least one field")   end end 


回答3:

Here's a reusable version:

class AnyPresenceValidator 

You can use it in your model with:

validates_with AnyPresenceValidator, fields: %w(field1 field2 field3) 


回答4:

I believe something like the following may work

class MyModel 


回答5:

Going further with @Votya's correct answer, here is a way to retrieve all columns besides created_at and updated_at (and optionally, any others you want to throw out):

# Get all column names as an array and reject the ones we don't want Model.content_columns.map(&:name).reject {|i| i =~ /(created|updated)_at/} 

For example:

 1.9.3p327 :012 > Client.content_columns.map(&:name).reject {|i| i =~ /(created|updated)_at/}  => ["primary_email", "name"] 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!