Search code examples
ruby-on-railsbelongs-tosti

Rails: belongs_to association not returning the correct object


I've got an Order model with two belongs_to associations, each to a different sub-class of my Account model. After loading an order from the database, both associations point to the same model, even though the foreign keys are correct.

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

Console does something like this:

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

The foreign key values are correct, but the object referenced by the association is not! What am I doing wrong?


Solution

  • Make sure you don't have collisions with other methods! I left out a definition in the Order model:

    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
    

    Deleting the account method gave me the correct behavior.