0

我想我遇到了这个问题,因为我的子类可以属于一个父级或另一个父级,但不能同时属于两者。让我向您展示我的代码,然后是错误。

class Purchase < ActiveRecord::Base # my child class
  # columns = user_id, price_id and unit_price_id
  belongs_to :user
  belongs_to :price
  belongs_to :unit_price

  scope :today, lambda { joins(:unit_price, :price).
                             where(:price => { :date => Date.today },
                                   :unit_price => { :date => Date.today } ) }
  def total
    self.price.sum(:amount) + self.unit_price.sum(:amount)
  end
end

在我看来,我尝试这样做:

<%= number_to_currency(current_user.purchases.today.map(&:total)) %>

但这给了我错误:

PGError: ERROR:  missing FROM-clause entry for table "price"
LINE 1: ...s"."price_id" WHERE "purchases"."user_id" = 3 AND "price"."d...
                                                             ^
: SELECT "purchases".* FROM "purchases" INNER JOIN "unit_prices" 
ON "unit_prices"."id" = "purchases"."unit_price_id" 
INNER JOIN "prices" ON "prices"."id" = "purchases"."price_id" 
WHERE "purchases"."user_id" = 3 AND "price"."date" = '2012-08-16' 
AND "unit_price"."date" = '2012-08-16'

我真的不知道它到底在说什么,但有一个想法是 price_id 为零。它是否正确?如果是这样,我该如何解决这个问题?我是否应该创建两个单独的购买模型,称为 PricePurchase 和 UnitPricePurchase 作为修复?

让我知道你的想法。

谢谢你。

4

1 回答 1

3

表没有别名,并且它们的名称是复数形式(prices,而不是priceWHERE),因此这种更改可能会有所帮助:

where(:prices => { :date => Date.today },
                               :unit_prices => { :date => Date.today } ) }
于 2012-08-17T11:30:24.673 回答