Reputation: 91
I have a trouble validating one form, I have a Product model with several attributes, but I would like to make a method for validate the presence of almost one attribute of the following:
Product.rb
attr_accessible :ship_int, ship_df, :tipo_envio
#I'm trying to validate :ship_df like this:
validates :ship_df, :presence => { :message => "*seleciona al menos una opcion de envio"},
:allow_blank => true, :on => :create, :if => :almost_one_option_df?
def almost_one_option_df?
ship_df != nil || tipo_envio != nil || ship_int != nil
end
The question is, how can I validate the presence of almost one of those three attributes?, if one is presence the Product can be created.
Thanks!
Upvotes: 0
Views: 80
Reputation: 20069
I think you want to validate that at least one of ship_df
, tipo_envio
or ship_int
is set? If one, or two, or three of them have a value it is valid, but if none of the have a value it is not?
If so, I'd check for blank
not nil
:
validate :any_present?
def any_present?
if %w(ship_df tipo_envio ship_int).all?{|attr| self[attr].blank?}
errors.add :base, "*seleciona al menos una opcion de envio"
end
end
Upvotes: 1