Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validates_presence_of if condition on rails 3.2 and mongoid + simple_form

I want validate presence of these 2 attributes :shipping_cost and :shipping_cost_anywhere if the attribute :shipping is equal to true. and If

I have this in my model but not working fine for me:

validates_presence_of :shipping_cost, :shipping_cost_anywhere, :allow_blank => "true" if :shipping == "true"

this is my :shipping attribute:

field :shipping, :type => Boolean, :default => "false"

How can I do it?

Thank you!

Edited.

I'm using mongoid and simple_form gems

like image 327
hyperrjas Avatar asked Nov 27 '22 22:11

hyperrjas


2 Answers

validates_presence_of :shipping_costs_anywhere, :if => :should_be_filled_in?

def should_be_filled_in?
  shipping_costs_anywhere == "value"
end

The method will return true or false when it's called in the statement. No need to put colon in front of shipping_costs_anywhere.

like image 137
dennis Avatar answered Dec 06 '22 08:12

dennis


The fix for me to this question is the next code:

validates :shipping_cost, :shipping_cost_anywhere, :presence => true, :if => :shipping?

Thank you to all for your help but any answer has worked for me. thanks!

like image 29
hyperrjas Avatar answered Dec 06 '22 09:12

hyperrjas