【发布时间】:2011-02-09 01:20:48
【问题描述】:
我正在构建一个包含大量月度总计报告的应用程序。它们中的大多数都非常相似,它们现在都在工作,但是代码很糟糕。我必须清理它并试图找出这样做的最佳方法。
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
【问题讨论】:
-
您可能想看看has_scope gem。
-
欧根,谢谢你的建议。我可能会尝试这样做,但对自己可能做到这一点的方式更感兴趣(一种学习经验)。我知道有诸如 constantize 和 klass 之类的东西。我想看看它们是否能像 scopify 或类似的东西一样工作。
标签: ruby-on-rails-3 activerecord controller scope