This blog has been archived. Our writing has moved to makandra cards.
The blog of , a Ruby on Rails development team

Remembering the difference between belongs_to and has_one

One question that comes up frequently when teaching Rails is when to use belongs_to as opposed to has_one, and which table has the association id.

Here's a simple memory aid: A farmer has_many cows. Each cow belongs_to a farmer. To know which cows are his, the farmer brands his cows with tattoos. The tattoo is his farmer_id.

Going with this picture, your two tables look like this:

create_table 'farmers' do |t|
  t.string 'name'
end

create_table 'cows' do |t|
  t.integer 'farmer_id'
end

And here are the classes that go with it:

class Farmer
  has_many :cows
end

class Cow
  belongs_to :farmer
end
Growing Rails Applications in Practice
Check out our e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Recent posts

Our address:
makandra GmbH
Werner-von-Siemens-Str. 6
86159 Augsburg
Germany
Contact us:
+49 821 58866 180
info@makandra.de
Commercial register court:
Augsburg Municipal Court
Register number:
HRB 24202
Sales tax identification number:
DE243555898
Chief executive officers:
Henning Koch
Thomas Eisenbarth