我想了解RoR中的has_one
关系。
假设我有两个模型 - Person
和Cell
:
class Person < ActiveRecord::Base
has_one :cell
end
class Cell < ActiveRecord::Base
belongs_to :person
end
我可以在has_one :person
模型中使用belongs_to :person
代替Cell
吗?
不一样吗?
答案 0 :(得分:157)
不,它们不可互换,并且存在一些真正的差异。
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
对于双向关联,你需要其中一个,他们必须进入正确的班级。即使是单向关联,你使用哪一个也很重要。
答案 1 :(得分:11)
如果您添加“belongs_to”,那么您将获得双向关联。这意味着你可以从一个人那里得到一个人,从这个人那里得到一个细胞。
没有真正的区别,两种方法(使用和不使用“belongs_to”)都使用相同的数据库模式(单元数据库表中的person_id字段)。
总结:除非您需要模型之间的双向关联,否则不要添加“belongs_to”。
答案 2 :(得分:7)
使用两者都可以从Person和Cell模型中获取信息。
@cell.person.whatever_info and @person.cell.whatever_info.