Skip to content

Instantly share code, notes, and snippets.

@oojikoo-gist
Created February 12, 2015 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oojikoo-gist/8527e1c026a88b2e1718 to your computer and use it in GitHub Desktop.
Save oojikoo-gist/8527e1c026a88b2e1718 to your computer and use it in GitHub Desktop.
rails: associations

Using Associations

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”

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment