belongs_to
和has_one
之间的区别是什么?
阅读Ruby on Rails指南并没有帮助我。
答案 0 :(得分:200)
他们基本上做同样的事情,唯一的区别是你所处的关系的哪一方面。如果User
有一个Profile
,那么User
课程中您有has_one :profile
,而Profile
课程中您有belongs_to :user
课程User
}。要确定谁“拥有”另一个对象,请查看外键的位置。我们可以说Profile
“有profiles
因为user_id
表格有profile_id
列。但是,如果users
表上有一个名为Profile
的列,我们会说User
有一个{{1}},并且将交换belongs_to / has_one位置。
here是一个更详细的解释。
答案 1 :(得分:40)
关于外键所在的位置。
class Foo < AR:Base
end
belongs_to :bar
,那么foos表格会有bar_id
列has_one :bar
,则条形图表中有foo_id
列在概念层面,如果您的class A
与has_one
有class B
的关系,则class A
是class B
的父级,因此您的class B
与belongs_to
有class A
的关系,因为它是class A
的孩子。
两者都表达了1-1的关系。差异主要在于放置外键的位置,该外键位于声明belongs_to
关系的类的表中。
class User < ActiveRecord::Base
# I reference an account.
belongs_to :account
end
class Account < ActiveRecord::Base
# One user references me.
has_one :user
end
这些类的表可能类似于:
CREATE TABLE users (
id int(11) NOT NULL auto_increment,
account_id int(11) default NULL,
name varchar default NULL,
PRIMARY KEY (id)
)
CREATE TABLE accounts (
id int(11) NOT NULL auto_increment,
name varchar default NULL,
PRIMARY KEY (id)
)
答案 2 :(得分:4)
has_one
和belongs_to
在某种意义上通常是相同的,因为它们指向其他相关模型。 belongs_to
确保此模型已定义foreign_key
。
has_one
确保定义了其他模型has_foreign
键。
更具体地说,relationship
有两面,一面是Owner
,另一面是Belongings
。如果仅定义has_one
,我们可以获取Belongings
但无法从Owner
获取belongings
。要跟踪Owner
我们需要在所属模型中定义belongs_to
。
答案 3 :(得分:0)
我想补充的另一件事是,假设我们有以下模型关联
class Author < ApplicationRecord
has_many :books
end
如果我们只编写上述关联,那么我们可以通过
获取特定作者的所有书籍@books = @author.books
但对于某本书,我们无法通过
获得相应的作者@author = @book.author
要使上面的代码工作,我们还需要添加与Book模型的关联,就像这样
class Book < ApplicationRecord
belongs_to :author
end
这会将方法'author'添加到Book模型。
有关模式的详细信息,请参阅guides
答案 4 :(得分:0)
从简单性的角度来看,belongs_to
比has_one
更好,因为在has_one
中,您必须向具有外键的模型和表添加以下约束,以强制执行has_one
关系:
validates :foreign_key, presence: true, uniqueness: true