Rails: belongs_to 关联没有返回正确的对象

Rails: belongs_to association not returning the correct object

我有一个带有两个 belongs_to 关联的订单模型,每个关联到我的帐户模型的不同子 class。从数据库加载订单后,两个关联都指向同一个模型,即使外键是正确的。

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">

外键值正确,但关联引用的对象不正确!我做错了什么?

确保您没有与其他方法发生冲突!我在订单模型中遗漏了一个定义:

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

删除帐户方法给了我正确的行为。