我正在构建一个包含一堆每月总计报告的应用程序。他们中的大多数非常相似,他们现在都在工作,但代码很糟糕。我必须清理它并试图找出最佳方法。
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种这样的方法,我想弄清楚我是否将它传递给了一个活跃或不活跃的参数
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
答案 0 :(得分:0)
我找到了一种独特的方法来做到这一点。我创建了一个名为pie_chart和bar_chart的方法,它处理请求的HTML和JSON并实现了这个结构
/reports/:method/:year/:name/
send(params[:method],@current_account.items.send(params[:scope], params[:year]))
网址为/ reports / pie_chart / 2010 / count_types_by_year
我的控制器中有一个pie_chart方法,我的模型中有一个count_types_by_year作为范围,就像一个魅力完全使它变得动态,也使它适用于新添加... DRY baby DRY