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
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.
Comments
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
validates_presence_of :one, :two, :three, :four also worksvalidates 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.:email => true, but you get the idea.