1

因此,我正在尝试使用以下测试来测试我的模型关联:

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'

我究竟做错了什么?

更新: 问题出在 ':as => :customer' 位。但我真正的问题是测试。我应该在创建项目时分配订单。

4

2 回答 2

1

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

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

请参阅指南:as中的选项。

于 2013-05-31T04:06:35.947 回答
0

我认为项目应该通过订单属于_客户

class Item < AR:Base
  belongs_to :order
  belongs_to :customer, :class_name => Person, :through => :order
end
于 2013-05-31T03:47:11.377 回答