Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 validates rule based on action

This seems like a simple question but I can't seem to find an answer short of writing custom validators. I have this validator

validates :password, :presence => true, :confirmation => true, :length => { :minimum => 5}

there are more rules applied such as some regex for complexity, but this gives the gist.

The issue is that I only want presence applied on create, everything else needs to be on create and update. Because the user may not be changing a password when updating their information.

I tried splitting the rules

validates :password, :presence => true, :on => :create
validates :password, # The rest of the rules

This resulted in all rules being ignored for update. Is there a simple way to apply only one rule to create and the rest to everything?

like image 710
Jeremy B. Avatar asked May 05 '11 14:05

Jeremy B.


People also ask

How does validation work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.

What is the difference between validate and validates in rails?

So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.

How do I validate in Ruby on Rails?

This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".


1 Answers

You can try keeping it in one line, but applying :on => :create to just the :presence check:

validates :password, :presence => {:on => :create}, :confirmation => true, :length => { :minimum => 5}

However, I'm not sure it makes sense to always require a minimum length, but not always require presence -- if you update an existing record with a blank password, it's going to fail validations anyway since the length is 0.

like image 136
Dylan Markow Avatar answered Sep 19 '22 14:09

Dylan Markow