Mathieu Mahé
Mathieu Mahé

Reputation: 2746

Rails validations and belongs_to association

In my rails projects I have a lot of association tables. And I have some validations. Nothing really difficult, and it works almost every times.

But from time to time (like tonight), I have to switch from

  validates_presence_of :project_id
  validates_presence_of :tag_id

  validates_uniqueness_of :project_id, :scope => [:tag_id]

to

  validates_presence_of :project
  validates_presence_of :tag

  validates_uniqueness_of :project, :scope => [:tag]

Do you know the difference ? Do you if one is better than the other ?

Upvotes: 0

Views: 155

Answers (1)

joshua.paling
joshua.paling

Reputation: 13952

From the Rails Guides: http://guides.rubyonrails.org/active_record_validations.html#presence

2.9 presence This helper validates that the specified attributes are not empty. It uses the blank? method to check if the value is either nil or a blank string, that is, a string that is either empty or consists of whitespace.

class Person < ActiveRecord::Base
  validates :name, :login, :email, presence: true  
end

If you want to be sure that an association is present, you'll need to test whether the associated object itself is present, and not the foreign key used to map the association.

class LineItem < ActiveRecord::Base
  belongs_to :order
  validates :order, presence: true
end

So, you should use the second example you gave, which tests if the associated object itself is present, and not the first example, which only tests if the foreign key used to map the association is present.

Upvotes: 2

Related Questions