Search code examples
ruby-on-railsvalidationmodels

Form validation - if something is false, require this validation


In my form validation of my model, I'm trying to say that if the params of a column called :virtual is false, then the :location field should validate for :presence => true.

My current code is:

validates :location, if :virtual => false, :presence => true

But that's giving me a syntax error. What's the correct way to format this?


Solution

  • Something like:

    attr_accessor :virtual  # sets up a "virtual attribute" called "virtual" to which you can read/write a value
                            # this step isn't necessary if you already have an attribute on the model called "virtual"
    
    validates :location, :presence => true, :unless => :virtual?
    

    The use of virtual? should check whether the attribute virtual is true or false. Using unless means this validation is only performed if virtual is false (or is a value that is considered false).

    More detail on virtual attributes and validation: Rails: Using form fields that are unassociated with a model in validations