Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 361
deb Avatar asked May 13 '10 00:05

deb


2 Answers

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.

like image 53
Voyta Avatar answered Oct 07 '22 06:10

Voyta


Here's a reusable version:

class AnyPresenceValidator < ActiveModel::Validator   def validate(record)     unless options[:fields].any?{|attr| record[attr].present?}       record.errors.add(:base, :blank)     end   end end 

You can use it in your model with:

validates_with AnyPresenceValidator, fields: %w(field1 field2 field3) 
like image 44
Shai Coleman Avatar answered Oct 07 '22 06:10

Shai Coleman