克隆rails中的关系

Yul*_*ule 9 ruby-on-rails rails-activerecord rails-4-2-1 adequate-record

我在升级到rails 4.2.1时遇到了弃用错误, Modifying already cached Relation. The cache will be reset. Use a cloned Relation to prevent this warning.

我正在尝试运行的操作获得已登录的月份用户数.

我的测试很简单:

get :page
expect(response).to be_success
Run Code Online (Sandbox Code Playgroud)

控制器动作:

def page
  @months = {}
  (0..11).each do |month|
     @months[month] = User.group(:usergroup).number_first_logged_in(Date.new(Date.today.year,month+1, 1))
  end
end
Run Code Online (Sandbox Code Playgroud)

用户模型

class Model < ActiveRecord::Base
   ...
   def number_first_logged_in(month)
     where(first_logged_in_at: month.beginning_of_month..month.end_of_month).count
   end
end
Run Code Online (Sandbox Code Playgroud)

我意识到我运行了几乎相同的查询12次,但参数不同.当用户未分组时,此方法在别处使用.如何按照弃用警告中的建议"克隆"关系?

我不想简单地忽略这一点,因为它在运行测试时填满了我的屏幕,这不是很有帮助

mar*_*006 5

在我的例子中,是squeel gem产生了弃用警告.一个简单的monkeypatch修复了警告.

module Squeel
  module Adapters
    module ActiveRecord
      module RelationExtensions

        def execute_grouped_calculation(operation, column_name, distinct)
          super
        end

      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我不确定它是否会破坏吱吱声的行为,但它对我有用.Rails 4.2.x与squeel相结合似乎是一个问题.我还把它推进了squeel问题跟踪器https://github.com/activerecord-hackery/squeel/issues/374.