Search code examples
ruby-on-railsvalidationruby-on-rails-3model

Rails - How to validate a field only if a another field has a certain value?


In my form I have a Select with three values: Apple, Banana and Cherry. If I choose Apple from the select I hide another Select- and a Text-field with some Javascript, because when Apple is chosen, there is no need to fill in these other two fields anymore.

So now I have a problem with validating my form when it's submitted. I've found some similar problems for example in the case of "Only validate a field if another is blank."

This problem was solved like this:

validates_presence_of :mobile_number, :unless => :home_phone?

So I've just tried the first thing which popped into my mind:

validates_presence_of :state, :granted_at, :if => :type != 1

But when I run it, I get this error:

undefined method `validate' for true:TrueClass

How can I conditionally perform a validation on a field based on whether or not another field has a particular value?


Solution

  • Because it is executable code you need to wrap it in a lambda or a Proc object like so:

    validates_presence_of :state, :granted_at, :if => lambda { |o| o.type != 1 }
    
    # alternatively:
    ..., :if => lambda { self.type != 1 }
    ..., :if => Proc.new { |o| o.type != 1 }
    ..., :if ->(o) { o.type != 1 }