0

我有两个模型(Person 和 Customer),它们使用 Rails 的“type”参数在 DB 中共享一个表来分隔它们:

# Person.rb
class Person < ActiveRecord::Base
  ...
end

# Customer.rb
class Customer < Person
  has_many :orders
end

还有一个订单表:

class Order < ActiveRecord::Base
  belongs_to :customer
end

我正在运行测试以检索在过去 90 天内订购的客户:

# Inside of Customer.rb
  def self.ordered_in_last_90_days
    scoped.joins(:orders).where('orders.created_at > ?', 90.days.ago)
  end

但我收到以下错误:

ActiveRecord::StatementInvalid:
   SQLite3::SQLException: no such column: orders.customer_id: SELECT "people".* FROM "people" INNER JOIN "orders" ON "orders"."customer_id" = "people"."id" WHERE "people"."type" IN ('Customer') AND (orders.created_at > '2013-06-18 16:47:44.726372')

联接在寻找“orders.person_id”时正在寻找“orders.customer_id”。我该如何进行此更正?

4

1 回答 1

3

您需要指定foreign_key:

 class Customer < Person
   has_many :orders, foreign_key: person_id
 end
于 2013-09-16T17:03:53.233 回答