Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: validates :presence => true vs validates_presence_of

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.

like image 847
Aaric Pittman Avatar asked Mar 25 '11 19:03

Aaric Pittman


People also ask

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 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.

Can we save an object in the DB if its validations do not pass?

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.


2 Answers

All those validates_whatever_of :attr macros do is call validates :attr, :whatever => true.

The problem is you are using validate and not validates.

like image 141
scragz Avatar answered Sep 21 '22 03:09

scragz


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 
like image 27
sergserg Avatar answered Sep 23 '22 03:09

sergserg