Rails中“has_one”和“belongs_to”之间的差异

时间:2012-05-07 12:37:17

标签: ruby-on-rails

有什么区别?的优点和缺点?这对我来说有点混乱。

感谢。

3 个答案:

答案 0 :(得分:6)

当关系为 1-1 时,您将 belongs_to 放入带有外键的表格中,将 has_one 置于引用的表格中。

当关系 1-n belongs_to 放入带有外键的表格中,并将 has_many 放在引用的表格中>

答案 1 :(得分:5)

属于使用外键的表。对于以下内容:

class User < ActiveRecord::Base
  has_one :profile
end
class Profile < ActiveRecord::Base
  belongs_to :user
end

配置文件表需要有一个user_id字段来引用users表中的记录。

知道哪个属于哪个以及哪个是has_one是很多人都在努力的事情。一般来说,如果has_one可能会成为has_many,那么那就是需要has_one的那一面。

答案 2 :(得分:3)

你需要两者。 你是同一个班级的一个,另一个是你想要连接的班级。

e.g。

Class User 
  has_one :profile
end

Class Profile
  belongs_to :user
end

正确设置关系后,优势在于您可以使用user.profileprofile.user访问它们。