私は一ヶ月の合計レポートを持つアプリケーションを構築しています。それらのほとんどは非常によく似ていて、今はすべて動作していますが、コードはうんざりです。私はこれをきれいにして、そうすることで最善の方法を見つけようとしています。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つの合計のメソッドを持っていると私はそれを
params[:active]
アクティブまたは非アクティブのPARAMを渡すと、私はこの呼び出し に添付することができるかどうかを把握しようとしています
@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)gem。 – eugen
オイゲン、提案していただきありがとうございます。私はそれを試みるかもしれないが、おそらくこれを自分自身で行う方法(学習経験の一種)にもっと興味があった。私は、一定化やクラスなどがあることを知っています。これらがscopifyのように動作するかどうかを見たいと思います。 – bokor