When should I validate the presence of an ActiveRecord association object vs its id?

Viewed 1961

Suppose I have an ActiveRecord association like:

class City < ActiveRecord::Base
  belongs_to :state
end

A city without a state should be invalid. It seems that both of these are possible validations:

validates :state,    presence: true
# OR
validates :state_id, presence: true

I would guess that they are identical, since:

  • belongs_to creates methods state and state=
  • state= sets the state_id

However, I've just fixed a failing spec by changing it to check for the id instead of the object.

Are these two ways of validating both acceptable? If so, when would you use one or the other?

4 Answers
Related