Bla*_*man 140 activerecord ruby-on-rails
a belongs_to
和a有has_one
什么区别?
阅读Ruby on Rails指南并没有帮助我.
rye*_*guy 217
他们基本上做同样的事情,唯一的区别是你所处的关系的哪一方面.如果a User
有a Profile
,那么User
你将has_one :profile
在Profile
课堂上和课堂上有belongs_to :user
.要确定谁"拥有"另一个对象,请查看外键的位置.我们可以说User
"有"a Profile
因为profiles
表有user_id
列.但是,如果profile_id
在users
表上有一个列,我们会说a Profile
有一个User
,并且belongs_to/has_one位置将被交换.
这里有一个更详细的解释.
小智 44
它是关于外键所在的位置.
class Foo < AR:Base
end
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
这些类的表可能类似于:
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)
)
Run Code Online (Sandbox Code Playgroud)
has_one
并且belongs_to
通常在某种意义上是相同的,它们指向另一个相关模型。belongs_to
确保该模型具有foreign_key
定义。
has_one
确保has_foreign
定义了另一个模型键。
更具体地说, 有两个方面relationship
,一个是Owner
,另一个是Belongings
。如果只has_one
定义了,我们可以得到它,Belongings
但不能Owner
从belongings
. 为了追踪Owner
我们需要belongs_to
在归属模型中定义。
归档时间: |
|
查看次数: |
40628 次 |
最近记录: |