Quick quiz, hotshot: suppose users have a “status”: active, inactive, pensive, etc. What’s the right association?
class User < ActiveRecord::Base
belongs_to :status # this?
has_one :status # or this?
end
Hrm. Most likely, you want belongs_to :status. Yeah, it sounds weird. Don’t think about the phrase “has_one” and “belongs_to”, consider the meaning:
- belongs_to: links_to another table. Each user references (links to) a status.
- has_one: linked_from another table. A status is linked_from a user. In fact, statuses don’t even know about users – there’s no mention of a “user” in the statuses table at all. Inside class Status we’d write has_many :users (has_one and has_many are the same thing – has_one only returns 1 object that links_to this one). A mnemonic:
“belongs_to” rhymes with “links_to” “has_one” rhymes with “linked_from”