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