0
我建立有一堆每月總計報告的應用程序。他們中的大多數非常相似,他們現在都在工作,但代碼很糟糕。我必須清理它並試圖找出最好的方法。的Rails 3 - 請求參數變成範圍調用
def active_monthly_total_by_type
respond_to do |format|
format.html
format.json {
@results = @current_account.items.totals_by_month(params[:selected_year], :status_change_date).with_type.active
render :json => @results.collect{ |result| { :type => result.type, :jan => result.jan, :feb => result.feb, :mar => result.mar, :apr => result.apr, :may => result.may, :jun => result.jun, :jul => result.jul, :aug => result.aug, :sep => result.sep, :oct => result.oct, :nov => result.nov, :dec => result.dec } }
}
end
end
def active_monthly_total
respond_to do |format|
format.html
format.json {
@results = @current_account.items.totals_by_month(params[:selected_year], :status_change_date).active
render :json => @results.collect{ |result| { :jan => result.jan, :feb => result.feb, :mar => result.mar, :apr => result.apr, :may => result.may, :jun => result.jun, :jul => result.jul, :aug => result.aug, :sep => result.sep, :oct => result.oct, :nov => result.nov, :dec => result.dec } }
}
我有6層總的方法是這樣,我想弄清楚,如果我通過它的PARAM活性或非活性
params[:active]
,如果我可以把它連接到該呼叫
@results = @current_account.items.totals_by_month(params[:selected_year], :status_change_date).params[:active]
如果有人能幫助或者給我一些建議,我可以找資料,我很想有控制所有這些要求,因爲它們是同一個方法。這裏是模型範圍:
def self.totals_by_month(year, date_type)
start_date = year.blank? ? Date.today.beginning_of_year : Date.parse("#{year}0101").beginning_of_year
end_date = year.blank? ? Date.today.end_of_year : Date.parse("#{year}0101").end_of_year
composed_scope = self.scoped
start_date.month.upto(end_date.month) do |month|
composed_scope = composed_scope.select("COUNT(CASE WHEN items.#{date_type.to_s} BETWEEN '#{start_date.beginning_of_month}' AND '#{start_date.end_of_month}' THEN 1 END) AS #{Date::ABBR_MONTHNAMES[month].downcase}")
start_date = start_date.next_month
end
composed_scope
end
你可能想看看[has_scope]( https://github.com/plataformatec/has_scope)寶石。 – eugen 2011-02-09 10:19:44