在Model类方法中指定当前抓取的记录

Nei*_*eil 6 ruby activerecord ruby-on-rails activerecord-relation

我有一个类方法,我想修改当前由ActiveRecord::Relation对象抓取的记录.但我不知道如何在类方法中引用当前作用域. self不这样做.

例:

class User < ActiveRecord::Base
  ...

  def self.modify_those_records
    #thought implicitly #to_a would be called on currently grabbed records but doesn't work
    temp_users_to_a = to_a
    ...
  end
end
Run Code Online (Sandbox Code Playgroud)

我会像这样使用它:

User.some_scope.modify_those_records
Run Code Online (Sandbox Code Playgroud)

所以User.some_scope会回到我身边ActiveRecord::Relation,其中包含一堆User记录.然后,我想修改该类方法中的那些记录,然后返回它们.

问题是:我不知道如何在类方法中明确引用"那组记录".

MrY*_*iji 5

您可以使用current_scope

def self.modify_those_records
  current_scope.each do |user|
    user.do_something!
  end
end
Run Code Online (Sandbox Code Playgroud)

如果您想根据管理员权限对用户进行排序,最好使用 ActiveRecord:

scope :order_admins_first, order('CASE WHEN is_admin = true THEN 0 ELSE 1 END, id')
User.some_scope.order_admins_first
Run Code Online (Sandbox Code Playgroud)

此代码暗示您is_admin在用户表上有一个布尔列。