I don't understand difference of those 2 association types.
For example, we have 2 tables:
boxers
[ id, name, title ]
titles
[ id, name ]
So, we can specify our associations this way:
boxer.rb
belongs_to :title, forign_key: "title"
And then use it like Boxer.find(1).title.name
Logically, each boxer always has one record in titles and each title has many boxers.
So why wouldn't we specify has_one
and has_many
relations? And when i specify belongs_to :title, forign_key: "title"
, it means that FK point on table boxers in my case (boxer.rb). But when I try to write has_one :title, forign_key: "title"
, it search column title
in titles
table. Why?
I think the confusion may stem from the association between your models being somewhat counterintuitive. You're saying each
boxer
has onetitle
, but eachtitle
may have multipleboxers
, correct? In that case, while intuitively we'd talk about titles belonging to boxers, your association should actually be the other way around: each title has many boxers, and each boxer belongs to one title. So:Where you have a
has_one
orhas_many
association in Rails, the other side must always havebelongs_to
, and this should be on the model that has the foreign_key to the other table. From the above, Rails would normally assume that theboxers
table has a column calledtitle_id
, which would correspond to the values in theid
column oftitles
. Given you've not done that, you'll need to provide the additional information so Rails can properly handle the association.Specifically, you'll need to tell Rails that the Boxer model is using
title
as it's foreign key, and that this corresponds to the Title'sname
:I'd recommend instead moving to a more standard setup, and dropping the
title
field on boxer in favour of atitle_id
. It's probably also worth having a look through the RailsGuide on Active Record Associations, as that has quite a bit of detail on exactly how all this works.