这个问题在这里已经有答案了:

我试图理解 has_one RoR 中的关系。

假设我有两个模型 - PersonCell:

class Person < ActiveRecord::Base
  has_one :cell
end

class Cell < ActiveRecord::Base
  belongs_to :person
end

我可以只使用 has_one :person 代替 belongs_to :personCell 模型?

不是一样吗?

有帮助吗?

解决方案

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

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

对于双向关联,您需要各有一个,并且它们必须进入正确的类别。即使对于单向关联,使用哪一种关联也很重要。

其他提示

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

没有真正的区别,两种方法(有和没有“belongs_to”)使用相同的数据库模式(单元格数据库表中的 person_id 字段)。

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

使用两者可以让您从 Person 和 Cell 模型获取信息。

@cell.person.whatever_info and @person.cell.whatever_info.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top