0

私はこのクラスとその中にこれらのメソッドを持っています。

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

スコープチェーンを次のように使用しようとすると、次のようになります。

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

の空の配列結果が得られます[]。私は本当にこれをやろうとしています。

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

ただし、このエラーが発生した場合も、これは機能しません。

undefined method `to_f' for []:Array

なぜ空に戻るのですか?

ありがとう。

4

1 に答える 1

1

スコープtodayは、結果セットをゼロの結果に減らす必要があります。つまり、そもそもあるcurrent_user場合です。'sは実際にはpurchases?アソシエーションが存在することを確認しますか(存在しない場合はおそらくNoMethodErrorがスローされると思いますが)?PricedateDate:pricesPurchase

あなたundefined method to_f for []:Arrayの場合、空の配列で作業していなくても、配列をfloatとしてキャストしようとしていることになります。あなたはsumあなたが得るであろう価格の配列にしたいと思うでしょう、そしてそれをに渡しますnumber_to_currency

number_to_currency(current_user.purchases.today.map(&:total).sum)
于 2012-08-17T18:01:59.793 に答える