私のRailsアプリにはusers
、たくさん持つことができる人がいpayments
ます。
class User < ActiveRecord::Base
has_many :invoices
has_many :payments
def year_ranges
...
end
def quarter_ranges
...
end
def month_ranges
...
end
def revenue_between(range, kind)
payments.sum_within_range(range, kind)
end
end
class Invoice < ActiveRecord::Base
belongs_to :user
has_many :items
has_many :payments
...
end
class Payment < ActiveRecord::Base
belongs_to :user
belongs_to :invoice
def net_amount
invoice.subtotal * percent_of_invoice_total / 100
end
def taxable_amount
invoice.total_tax * percent_of_invoice_total / 100
end
def gross_amount
invoice.total * percent_of_invoice_total / 100
end
def self.chart_data(ranges, unit)
ranges.map do |r| {
:range => range_label(r, unit),
:gross_revenue => sum_within_range(r, :gross),
:taxable_revenue => sum_within_range(r, :taxable),
:net_revenue => sum_within_range(r, :net) }
end
end
def self.sum_within_range(range, kind)
@sum ||= includes(:invoice => :items)
@sum.select { |x| range.cover? x.date }.sum(&:"#{kind}_amount")
end
end
私の見解では、ユーザーが選択した GET パラメータに応じてdashboard
、合計支払いをリストしています。ranges
ユーザーは、、、またはのいずれかを選択years
できquarters
ますmonths
。
class DashboardController < ApplicationController
def show
if %w[year quarter month].include?(params[:by])
@unit = params[:by]
else
@unit = 'year'
end
@ranges = @user.send("#{@unit}_ranges")
@paginated_ranges = @ranges.paginate(:page => params[:page], :per_page => 10)
@title = "All your payments"
end
end
インスタンス変数 ( @sum
) を使用すると、SQL クエリの数が大幅に削減されます。これは、データベースが同じクエリに対して何度もヒットすることがないためです。
ただし、問題は、ユーザーが自分の のいずれかを作成、削除、または変更しても、インスタンス変数payments
に反映されないことです。@sum
では、どうすればリセットできますか?または、これに対するより良い解決策はありますか?
助けてくれてありがとう。