Differentiate between a has_one and belongs_to association in Ruby? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Differentiate between a has_one and belongs_to association in Ruby?

what is the main differences

22nd Mar 2018, 1:01 PM
S.NAGA DURGA SAI BABU
S.NAGA DURGA SAI BABU - avatar
1 Answer
+ 3
belongs_to will place the foreign key in the declaring model whereas has_one will place it in the other model. To sum things up: use belongs_to when you want the foreign key in the declaring model, use has_one if you want it on the other model. But anyway, you will rarely see a belongs_to or a has_one used alone. Most of the time it will be has_many with belongs_to for a one-to-many association and has_one with belongs_to for a one-to-one association.
31st Mar 2018, 7:38 PM
Baraa AB
Baraa AB - avatar