的得到了与所有has_one
和belongs_to
关系一个很有趣的情况时,Rails的加载其依赖的模型呈倒的方式。多发HAS_ONE同一类
让我们有一个模型Couple
与同一类的两个相关的模型,User
:
class Couple < ActiveRecord::Base
has_one :male, class_name: "User"
has_one :female, class_name: "User"
end
class User < ActiveRecord::Base
belongs_to :couple
end
在这种情况下,当我们创建一个Couple
并指定其为User
两个实例中,我们将进入这个:
# create all the stuff
couple = Couple.new
he = User.create name: 'Bob'
she = User.create name: 'Sara'
couple.male = he
couple.female = she
couple.save
# here's where the gap begins:
couple.male.name # => 'Bob'
couple.female.name # => 'Sara'
# Ok, so far so good...
Couple.find(couple.id).male.name # => 'Bob'
# What's the ..?!
Couple.find(couple.id).female.name # => 'Bob'
而我在执行所有这些控制台所看到的,是这样的:
> couple.female.name
'Sara'
# nothing happens as the model is loaded already
> Couple.find(couple.id).female.name
SELECT `couples`.* FROM `couples` WHERE `couples`.`id` = 2 LIMIT 1
SELECT `users`.* FROM `users` WHERE `users`.`couple_id` = 2 LIMIT 1
'Bob'
# sure, here's the trouble!
嗯...这不好...在互联网上搜索引导我到这个:我创建了两个类,MaleUser
和FemaleUser
,都来自User
模型。并改变了belongs_to :couple
到belongs_to :couple, foreign_key: :his_id
和... :her_id
。然而,我在屏幕上看到了同样的结果。
我的问题是,为什么发生这种情况到底如何以正确的方式执行加载?所以Couple.find(couple_id).she
会给我适当的对象?
UPD:表结构:
create_table :users do |t|
t.integer :couple_id
# ...
end
create_table :couples do |t|
t.integer :his_id
t.integer :her_id
# ...
end
谢谢!
你能还包括两个'User'和'Couple'表迁移/ SQL表结构? – Pete 2014-12-02 00:32:41
@Pete如果这能帮助......然而,没有什么真正有趣的或超自然的存在... – shybovycha 2014-12-02 00:36:04