在我的Rails应用程序中,我有users
谁可以有很多payments
。如何在Rails模型中更新实例变量?
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
鉴于我取决于用户选择了GET参数列出了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
实例变量中。那么我该如何重置它?还是有更好的解决方案呢?
感谢您的任何帮助。
+1,很好的解决方法。虽然我会让'sum_within_range'做所有使用SQL的计算(请参阅我的回答) –
@m_x ya通常情况会更好,但由于prev问题,我有一些bkgrnd。这个函数在相同的重叠范围请求中被调用了很多次,所以我认为最好在Rails中进行过滤。但如果不是这样的话,你的解决方案更有意义:) – tihom
谢谢。当我复制你的确切代码时,我仍然可以获得大约80个SQL查询。所以我将'includes(:invoice =>:items)'移动到'Payment'类的select方法的开头,现在每页只有大约10个SQL查询(与之前相同,因此也很好),但是总渲染时间已经增加了很多,从大约300毫秒到大约3000毫秒。这绝对是太多了,我想知道它为什么。 – Tintin81