So, I'm trying to test my models associations with the following test:
it 'retrieve items registered under person' do
p = FactoryGirl.create(:person)
o = FactoryGirl.create(:order, customer: p)
o.customer.should == p
i = FactoryGirl.create(:item)
o.items << i
o.save
p.items.count.should == 1
end
My models:
class Person < AR:Base
has_many :orders, :as => :customer
has_many :items, :through => :orders
end
class Order < AR:Base
has_many :items
belongs_to :customer, :class_name => Person
end
class Item < AR:Base
belongs_to :order
has_one :customer, :class_name => Person, :through => :order
end
But when I run the test it gives me the following error:
SQLite3::SQLException: no such column: orders.customer_type: SELECT COUNT(*) FROM "items" INNER JOIN "orders" ON "items"."order_id" = "orders"."id" WHERE "orders"."customer_id" = 1 AND "orders"."customer_type" = 'Person'
What am I doing wrong?
Update: The problem was on the ':as => :customer' bit. But my real problem was with the test. I should have assigned an order in the creation of an item.
It's because the :as
option specifies a polymorphic interface. This explains "orders"."customer_type" = 'Person'
in the where clause. I think what you mean to do is:
class Person < ActiveRecord::Base
has_many :orders, :foreign_key => :customer_id
has_many :items, :through => :orders
end
See the :as
option in the guide.