简体   繁体   English

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

[英]Specify currently grabbed records within Model class method

I have a class method where I want to modify the records that are currently grabbed by an ActiveRecord::Relation object. 我有一个类方法,我想修改当前由ActiveRecord::Relation对象抓取的记录。 But I don't know how to refer to the current scope in a class method. 但我不知道如何在类方法中引用当前作用域。 self does not do it. self不这样做。

Example: 例:

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

I would use it like this: 我会像这样使用它:

User.some_scope.modify_those_records

So User.some_scope would return to me an ActiveRecord::Relation that contains a bunch of User records. 所以User.some_scope会给我一个包含一堆User记录的ActiveRecord::Relation I then want to modify those records within that class method and then return them. 然后,我想修改该类方法中的那些记录,然后返回它们。

Problem is: I don't know how to explicitly refer to "that group of records" within a class method. 问题是:我不知道如何在类方法中明确引用“那组记录”。

You can use current_scope : 你可以使用current_scope

def self.modify_those_records
  current_scope.each do |user|
    user.do_something!
  end
end

If you want to order Users based on their admin rights, you would be better to use ActiveRecord: 如果您想根据用户的管理员权限订购用户,最好使用ActiveRecord:

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

This code implies that you have a boolean column is_admin on the users table. 此代码表示您在users表上有一个布尔列is_admin

I would argue that a combination of a scope with each and an instance method is easier to understand than a class method. 我认为范围与each实例方法的组合比类方法更容易理解。 And as a bonus it is easier to test, because you can test all steps in isolation: 作为奖励,它更容易测试,因为您可以单独测试所有步骤:

Therefore instead of User.some_scope.modify_those_records I would do something like: 因此,我会做以下事情而不是User.some_scope.modify_those_records

User.some_scope.each(&:modify)

and implement a instance method: 并实现一个实例方法:

# in user.rb
def modify
  # whatever needs to be done
end

如果您只想修改记录的顺序 - 更好的方法是将排序字段(如果您还没有)添加到模型中并按此排序。

User.some_scope.order(name: :asc).order(is_admin: :desc)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM