在我的 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
在我dashboard
看来,我列出了ranges
取决于用户选择的 GET 参数的总付款。用户可以选择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
(
然而,问题是,当用户创建、删除或更改其中一个时payments
,这不会反映在@sum
实例变量中。那么我该如何重置呢?或者有更好的解决方案吗?
谢谢你的帮助。