【问题标题】:has_many through association sql errorhas_many通过关联sql报错
【发布时间】:2013-05-26 15:20:24
【问题描述】:

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

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' 位上。但我真正的问题是测试。我应该在创建项目时分配订单。

【问题讨论】:

  • 订单表中可能没有customer_type列。
  • 是的,我知道了。但它为什么要寻找列 customer_type?
  • 你确定这些模型不使用单表继承吗?因为这会导致 ActiveRecord 查找 model_type
  • 你能发布你的 db/schema.rb 吗?

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


【解决方案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 选项。

【讨论】:

  • 确实如此, :as 确实用于多态关联。
【解决方案2】:

我认为商品应该通过订单属于_客户

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 2015-01-27
    相关资源
    最近更新 更多