What's the difference between belongs_to and has_one?

前端 未结 5 492
有刺的猬
有刺的猬 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:38

    They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile, then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user. To determine who "has" the other object, look at where the foreign key is. We can say that a User "has" a Profile because the profiles table has a user_id column. If there was a column called profile_id on the users table, however, we would say that a Profile has a User, and the belongs_to/has_one locations would be swapped.

    here is a more detailed explanation.

提交回复
热议问题