【问题标题】:Rails 3 - Request Params turn into Scope callsRails 3 - 请求参数变成范围调用
【发布时间】: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


【解决方案1】:

我找到了一种独特的方法来做到这一点。我创建了一个名为 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

【讨论】:

    猜你喜欢
    • 2014-12-09
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    相关资源
    最近更新 更多