I have this class and these methods inside of it.
class Purchase < ActiveRecord::Base
belongs_to :user
belongs_to :price
belongs_to :unit_price
scope :today, lambda { joins(:unit_price, :price).
where(:prices => { :date => Date.today },
:unit_prices => { :date => Date.today } ) }
# not working
def total
self.price.sum(:amount) + self.unit_price.sum(:amount)
end
end
When I try to use my scope chain like this:
<%= current_user.purchases.today.map(&:total) %>
It gives me an empty Array result of []. I’m really trying to do this.
<%= number_to_currency(current_user.purchases.today.map(&:total)) %>
But this doesn’t work either for this error occurs.
undefined method `to_f' for []:Array
Why does it come back empty?
Thanks.
Your
todayscope must be reducing the resultset to zero results. That is, ifcurrent_userhas anypurchasesin the first place. Are you sure aPrice‘sdateis actually aDate? Are you sure the:pricesassociation exists onPurchase(although I guess it would probably throw a NoMethodError there if it didn’t)?As for your
undefined method to_f for []:Array, even if you weren’t working with an empty array, you’d still be trying to cast your array as a float. You’ll want tosumthe array of prices you’ll get, and pass that tonumber_to_currency: