0

私の Rails 3.2.8 アプリケーションでは、すべてのユーザーの製品と税額の合計を計算しようとしています。製品の合計を取得してから、各製品の税を取得する必要があります。

class Product
  attr_accessible :amount, :location_id, :tax_id
  belongs_to :tax
  belongs_to :location
  belongs_to :user
  belongs_to :tax, :class_name => "Tax"

  def self.total
    self.sum(:amount) + self.tax.sum(:amount)
  end
end

Tax.rb

class Tax < ActiveRecord::Base
  attr_accessible :amount, :date, :location_id
  belongs_to :user
  belongs_to :location
  has_many :products
end

したがって、次のようなスコープを試すと:

<%= number_to_currency(current_user.products.total) %>

もちろん、これは私にエラーを与えます:

undefined method `tax' for #<Class:0x57f5298>

これを機能させるにはどうすればよいですか?

ありがとうございました。

4

3 に答える 3

3

taxクラス Product ではなく、Product のインスタンス メソッドです。

以下を試してください(パフォーマンスが低い):

class Product
  belongs_to :tax

  def self.total
    self.sum(:amount) + all.map(&:tax).map(&:amount).sum
  end
end
于 2012-08-29T14:16:05.013 に答える
1

私は ActiveRecord の新しいクエリ メソッドが苦手です。私は少し時代遅れで、SQL に傾倒する傾向がありますが、これは「効率的に」必要なものを取得する必要があります。

  def self.total
    self.select('sum(products.amount + taxes.amount) AS sum').joins(:tax).try(:sum, 0)
  end
于 2012-08-31T02:53:19.023 に答える
1

この行から

<%= number_to_currency(current_user.products.total) %>

現在のユーザーについては、彼の製品と税金の合計が必要であることを理解しました。以前に行ったことは、現在のユーザーではなく、製品のテーブル全体に関連しています。もちろん、このテーブルの一部の製品は現在のユーザーに関連していない可能性があります。

では、それはどうなんだろうと思うのですが。

#Instance method for current user
class User < ...
  def product_tax_total
    products.joins(:tax).select('SUM(products.amount + taxes.amount) AS sum').sum
  end
end

そして、次のように使用します。

<%= number_to_currency(current_user.product_tax_total) %>

アップデート:

スコープを使用してクエリをチェーンできます。

class Product
  scope :today, lambda { where(:date => Date.today) }
end

そして、それを連鎖させます

class User < ...
  def product_tax_total
    products.today.joins(:tax).select('SUM(products.amount + taxes.amount) AS sum').sum
  end
end
于 2012-09-01T20:38:32.213 に答える