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
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
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
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
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.