What's the difference between belongs_to and has_one?

前端 未结 5 377
有刺的猬
有刺的猬 2020-11-28 02:04

What is the difference between a belongs_to and a has_one?

Reading the Ruby on Rails guide hasn\'t helped me.

5条回答
  •  有刺的猬
    2020-11-28 02:52

    has_one and belongs_to generally are same in a sense that they point to the other related model. belongs_to make sure that this model has the foreign_key defined. has_one makes sure that the other model has_foreign key defined.

    To be more specific, there are two sides of relationship, one is the Owner and other is Belongings. If only has_one is defined we can get its Belongings but cannot get the Owner from the belongings. To trace the Owner we need to define the belongs_to as well in the belonging model.

提交回复
热议问题