简体   繁体   中英

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 ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM