我有一个类方法,我想在其中修改当前由 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
我会这样使用它:
User.some_scope.modify_those_records
所以 User.some_scope
会返回给我一个 ActiveRecord::Relation
,其中包含一堆 User
记录。然后我想在该类方法中修改这些记录,然后返回它们。
问题是:我不知道如何在类方法中明确引用“那组记录”。
最佳答案
您可以使用current_scope
:
def self.modify_those_records
current_scope.each do |user|
user.do_something!
end
end
如果您想根据用户的管理员权限对用户进行排序,您最好使用 ActiveRecord:
scope :order_admins_first, order('CASE WHEN is_admin = true THEN 0 ELSE 1 END, id')
User.some_scope.order_admins_first
此代码暗示您在用户表上有一个 bool 列 is_admin
。
关于ruby-on-rails - 在 Model 类方法中指定当前抓取的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36039827/