has_many通过关联sql错误

时间:2013-05-30 21:57:26

标签: ruby-on-rails ruby-on-rails-3 rspec sqlite rspec-rails

所以,我试图通过以下测试来测试我的模型关联:

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

我的模特:

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

但是当我运行测试时,它会给我以下错误:

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'

我做错了什么?

更新 问题出在&#39;:as =&gt; :客户&#39;位。但我真正的问题在于测试。我应该在创建项目时分配一个订单。

2 个答案:

答案 0 :(得分:1)

这是因为:as选项指定了多态接口。这解释了where子句中的"orders"."customer_type" = 'Person'。我想你的意思是:

class Person < ActiveRecord::Base
  has_many :orders, :foreign_key => :customer_id
  has_many :items, :through => :orders
end

请参阅guide中的:as选项。

答案 1 :(得分:0)

我认为Item应该通过订单属于客户

class Item < AR:Base
  belongs_to :order
  belongs_to :customer, :class_name => Person, :through => :order
end