belongs_to和has_one有什么区别?

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 :profileProfile课堂上和课堂上有belongs_to :user.要确定谁"拥有"另一个对象,请查看外键的位置.我们可以说User"有"a Profile因为profiles表有user_id列.但是,如果profile_idusers表上有一个列,我们会说a Profile有一个User,并且belongs_to/has_one位置将被交换.

这里有一个更详细的解释.

  • 所以说它真的很短:`产品belongs_to Shop`意味着`products`表有`shop_id`列 (42认同)

小智 44

它是关于外键所在的位置.

class Foo < AR:Base
end
Run Code Online (Sandbox Code Playgroud)
  • 如果是foo belongs_to :bar,则foos表有一bar_id
  • 如果是foo 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)

  • 这是一个更好的答案. (11认同)

ill*_*ist 5

has_one并且belongs_to通常在某种意义上是相同的,它们指向另一个相关模型。belongs_to确保该模型具有foreign_key定义。 has_one确保has_foreign定义了另一个模型键。

更具体地说, 有两个方面relationship,一个是Owner,另一个是Belongings。如果只has_one定义了,我们可以得到它,Belongings但不能Ownerbelongings. 为了追踪Owner我们需要belongs_to在归属模型中定义。