什么是belongs_to的和HAS_ONE之间的区别? [英] What's the difference between belongs_to and has_one?
问题描述
之间的区别是什么 belongs_to的
和 HAS_ONE
?
读Ruby on Rails的指南并没有帮助我。
Reading the Ruby on Rails guide hasn't helped me.
推荐答案
他们基本上做同样的事情,唯一的区别是你的关系是什么边。如果用户
有一个简介
,然后在用户
类,你就会有 HAS_ONE:简介
和简介
类,你不得不 belongs_to的:用户
。要确定谁拥有其他对象,看看那里的外键。我们可以说,一个用户
拥有一个简介
,因为配置文件
表中有一个 USER_ID
列。如果有一个名为 PROFILE_ID
在用户列
表,但是,我们可以说,一个简介
有一个用户
和belongs_to的/ HAS_ONE位置将被交换。
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.
这篇关于什么是belongs_to的和HAS_ONE之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!