belongs_to和has_one有什么区别?

时间:2010-09-28 00:49:16

标签: ruby-on-rails activerecord

belongs_tohas_one之间的区别是什么?

阅读Ruby on Rails指南并没有帮助我。

5 个答案:

答案 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
  • 如果foo belongs_to :bar,那么foos表格会有bar_id
  • 如果是foo has_one :bar,则条形图表中有foo_id

在概念层面,如果您的class Ahas_oneclass B的关系,则class Aclass B的父级,因此您的class Bbelongs_toclass 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_onebelongs_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_tohas_one更好,因为在has_one中,您必须向具有外键的模型和表添加以下约束,以强制执行has_one关系:

  • validates :foreign_key, presence: true, uniqueness: true
  • 在外键上添加数据库唯一索引。