【问题标题】:Difference between has_one and belongs_to in Rails? [duplicate]Rails中has_one和belongs_to的区别? [复制]
【发布时间】:2010-10-26 01:24:02
【问题描述】:

我正在尝试了解 RoR 中的 has_one 关系。

假设我有两个模型 - PersonCell

class Person < ActiveRecord::Base
  has_one :cell
end

class Cell < ActiveRecord::Base
  belongs_to :person
end

我可以在Cell 模型中只使用has_one :person 而不是belongs_to :person 吗?

不是一样的吗?

【问题讨论】:

  • 上面的代码不正确,应该是has_one :cellbelongs_to :person,冒号和后面的单词之间应该有空格。

标签: ruby-on-rails ruby has-one


【解决方案1】:

不,它们不可互换,并且存在一些真正的差异。

belongs_to 表示外键在这个类的表中。所以belongs_to 只能进入持有外键的类。

has_one 表示另一个表中存在引用该类的外键。所以has_one 只能进入另一个表中的列引用的类。

所以这是错误的:

class Person < ActiveRecord::Base
  has_one :cell # the cell table has a person_id
end

class Cell < ActiveRecord::Base
  has_one :person # the person table has a cell_id
end

这也是错误的:

class Person < ActiveRecord::Base
  belongs_to :cell # the person table has a cell_id
end

class Cell < ActiveRecord::Base
  belongs_to :person # the cell table has a person_id
end

正确的做法是(如果Cell包含person_id字段):

class Person < ActiveRecord::Base
  has_one :cell # the person table does not have 'joining' info
end

class Cell < ActiveRecord::Base
  belongs_to :person # the cell table has a person_id
end

对于双向关联,您需要每个关联,并且他们必须进入正确的班级。即使是单向关联,使用哪一个也很重要。

【讨论】:

  • 不错的答案。看到你的回答,我意识到我读了一半的问题。很抱歉,但很高兴你加入。+ 10
  • 我已经查了十亿次了。我希望他们能够更好地考虑命名,以便更清楚地说明哪个去哪里。
  • 太好了,现在我知道了两个错误的答案。最好显示“正确”的显示方式。只是说。
  • 我总是从玩具总动员的角度来考虑它。安迪'has_one'伍迪,伍迪'belongs_to'安迪。外键在哪里?在伍迪的鞋底上。
  • 这是一个很酷的助记符,但我想我会分享我的数学记忆方法。 has_one 类似于 has_many,has_many 表示键在另一个表上,因为在 SQL 表上定义了固定数量的列。
【解决方案2】:

如果您添加“belongs_to”,那么您将获得双向关联。这意味着您可以从单元格中获取一个人,并从该人中获取一个单元格。

没有真正的区别,两种方法(有和没有“belongs_to”)都使用相同的数据库架构(cells 数据库表中的 person_id 字段)。

总结:除非您需要模型之间的双向关联,否则不要添加“belongs_to”。

【讨论】:

  • 我今天读到的最好的一行:“如果你添加“belongs_to”,那么你就会得到一个双向关联。这意味着你可以从单元格中获取一个人,从那个人中获取一个单元格。” +1
【解决方案3】:

同时使用这两个模型可以让您从 Person 和 Cell 模型中获取信息。

@cell.person.whatever_info and @person.cell.whatever_info.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 2014-10-01
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多