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?
Generically, if you do not mention any thing, and just write the following:
And then you do:
boxer.title; it goes intotitlestable, and searchs there for a row where theidis same as theboxer_idstored in the object on which you are calling the methodboxer.title.That goes when you do not specify a
foreign_keyin the model.But if you do specify a
foreign_keylike following:Now, in
boxerstable, there must be a columntitlethat will store theidof of title it belongs to.The difference is just: If you do not specify a
foreign_key, it will go and look fortitle_id, but when you specify aforeign_key, it will search for that one instead.