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

You can follow any response to this post through the Atom feed.

Avatar

Sat, 06 Mar 2010 10:30:00 GMT

by henning

Tags:

Leave a comment