我有一个Order模型,其中有两个belongs_to关联,每个关联到Account模型的不同子类。从数据库加载订单后,即使外键是正确的,两个关联也指向相同的模型。
class Account < AR::Base
end
class FooAccount < Account
end
class BarAccount < Account
end
class Order < AR::Base
belongs_to :account, :class_name => 'FooAccount',
:foreign_key => :account_id
belongs_to :different_account, :class_name => 'BarAccount',
:foreign_key => :different_account_id
end
控制台做这样的事情:
o = Order.find(42)
=> #<Order id: 42, account_id: 11, different_account_id: 99>
a = Account.find(11)
=> #<FooAccount id: 11, type: "FooAccount">
d = Account.id(99)
=> #<BarAccount id: 99, type: "BarAccount">
o.account_id
=> 11
o.account
=> #<BarAccount id: 99, type: "BarAccount">
o.different_account_id
=> 99
o.different_account
=> #<BarAccount id: 99, type: "BarAccount">
外键值正确,但关联引用的对象不正确!我做错了什么?
确保不与其他方法发生冲突!我在Order模型中遗漏了一个定义:
class Order < AR::Base
belongs_to :account
# a lot and a lot of code
def account
# does a different lookup than the association above
end
end
删除帐户方法给了我正确的行为。