views:

244

answers:

3

Hi

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

+3  A: 

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
rspeicher
I believe it's not very good if there's a lot of fields :/
j.
I can't imagine he would want to check if one field _in his entire model_ is present. I assumed it was a particular set of fields.
rspeicher
your answer is also correct, so I voted it up as well. However, I ended up using Voyta's answer. Thanks for the reply!
deb
+2  A: 

I believe something like the following may work

class MyModel < ActiveRecord::Base
   validate do |my_model|
      my_model.my_validation
   end

   def my_validation      
      errors.add_to_base("Your error message") if self.blank? 
      #or self.attributes.blank? - not sure
   end
end
j.
+2  A: 

You can use:

validate :any_present?

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

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.

Voyta