Search code examples
rubyruby-on-rails-3ruby-on-rails-3.1

Missing FROM-clause entry for table because of nil columns?


I think I'm getting this issue because my Child Class can belong to one Parent or the other Parent but not both. Let me show you my code and then the error.

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

And than I try to do this in my view:

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

But this gives me the error:

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'

I really don't know exactly what its saying here but have an idea which is that the price_id is nil. Is this correct? If so how do I fix this issue? Should I create two seperate purchase models called PricePurchase and UnitPricePurchase as a fix?

Let me know what you think.

Thank you.


Solution

  • Tables aren't aliased and their names are in plural (prices, not price in WHERE), so perhaps this change would help:

    where(:prices => { :date => Date.today },
                                   :unit_prices => { :date => Date.today } ) }