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

时间:2015-07-15 18:35:00

标签: ruby-on-rails belongs-to sti

我有一个带有两个belongs_to关联的Order模型,每个关联到我的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">

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

1 个答案:

答案 0 :(得分:0)

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

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

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