看看 Rails 中的 ActiveRecord has_one 和 has_many 关系,这可能是一个普遍的(而且很可能是显而易见的)问题。
如果我有两个表,比如说 Husbands 和 Wives,它是一个一夫一妻制的所有已婚夫妇数据库,那么每个丈夫都有一个妻子,每个妻子都有一个丈夫。因此,将其视为一对夫妇的单 table 是有意义的。
为什么有人想要两个表,其中两个表都具有 has_one 关系,而不是将它们合并为一个表?
- 能否提高效率?
- 它能涵盖一些我没弄清楚的案例吗?
最佳答案
视情况而定。
如果:
- 你只对情侣感兴趣,
- 个人不持有任何数据,
- 每个人都有配偶,
那么,是的,使用单个表可能有意义。
但是,如果以上任何一项为假,您将需要使用个人记录。
你应该像这样声明关联:
class Person < ActiveRecord::Base
validates :gender, presence: :true
belongs_to :wife, -> { where gender: "F" },
foreign_key: :wife_id,
class: "Person"
has_one :husband, -> { where gender: "M" },
foreign_key: :wife_id,
class: "Person"
end
但是,如果您希望couple 记录也保存一些数据,您最好采用这种实现方式:
class Marriage < ActiveRecord::Base
validates :husband_id, presence: true
validates :wife_id, presence: true
belongs_to :husband, class: "Person"
belongs_to :wife, class: "Person"
end
class Person < ActiveRecord::Base
has_one :marriage
has_one :husband, though: :marriage
has_one :wife, though: :marriage
end
虽然你应该知道,如果一个 person = Person.find()
是一个,比方说,wife
,你调用 person.wife
,它可能会自行返回。
关于ruby-on-rails - 为什么要使用相互的 has_one 关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23423326/