我有两个模型(人员和客户)使用Rails的“type”参数在数据库中共享一个表来分隔它们:
# 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”。我怎样才能进行这种修正?
答案 0 :(得分:3)
您需要指定foreign_key:
class Customer < Person
has_many :orders, foreign_key: person_id
end