What is the difference between validates :presence
and validates_presence_of
? Looking through ActiveModel
it looks like they setup the validation the same way. However, given the following model definition:
class Account < ActiveRecord::Base has_one :owner_permission, :class_name => 'AccountPermission', :conditions => { :owner => true, :admin => true } has_one :owner, :class_name => 'User', :through => :owner_permission, :source => :user validate :owner, :presence => true validates_associated :owner end
Calling save on an instance of Account
does not validate the presence of owner. Though, if I use validates_presence_of
it will.
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.
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.
Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful. The following methods trigger validations, and will save the object to the database only if the object is valid: create.
All those validates_whatever_of :attr
macros do is call validates :attr, :whatever => true
.
The problem is you are using validate
and not validates
.
In Rails 3.x and 4.x - it is now encouraged to use the following syntax:
validates :email, presence: true validates :password, presence: true
Instead of the 2.x way:
validates_presence_of :email validates_presence_of :password
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With