1

I was wandering why in books like Agile Web Development with Rails there's no mention to validates_whatever_of way of validating, all validation examples are done using validates :attr, :whatever => true ? I've just started learning Rails and this made me confused!

2 Answers 2

2

In Rails 2.x, where you would have said something like:

validates_presence_of :user_name

in 3.x, you now do:

validates :username, :presence => true

The old way is still supported, I think, but it is deprecated.

It's really just a different way of expressing the same thing. While older books and tutorials will use the former, it should be fairly simple to translate that to 3.x style. See http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates for example.

Sign up to request clarification or add additional context in comments.

Comments

2

The validates syntax is just a new shortcut for the same thing. It's especially useful when you're validating a bunch of attributes with similar limits. So this:

validates_presence_of :one
validates_presence_of :two
validates_presence_of :three
validates_presence_of :four

can be reduced to

validates :one, :two, :three, :four, :presence => true

It's also a nice, consistent interface to custom validators.

3 Comments

but validates_presence_of :one, :two, :three, :four also works
Ah, I guess that's true. :-) It's probably contrived, but in the new scheme you can also validate other aspects using validates besides "presence" by tacking them onto validates. The best argument for the new scheme is that it's extensible without monkey patching ActiveRecord::Base. As in the example I liked to above, you can add a custom validator and it becomes available as option to validates. For example, creating an EmailValidator makes :valid => true available.
Err, I meant :email => true, but you get the idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.