ruby-on-rails - 在 Model 类方法中指定当前抓取的记录

标签 ruby-on-rails ruby activerecord 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

我会这样使用它:

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/

相关文章:

ruby-on-rails - Bundler 找不到 gem "nokogiri"的兼容版本

ruby-on-rails - Geokit ActiveModel::MissingAttributeError: 无法写入未知属性 `within`

python - 是否可以在 Python 中实现类似 Ruby 的内部 DSL?

ruby-on-rails - 尝试反序列化参数时 Shopify API 出错

ruby-on-rails - 将 Sidekiq 升级到 v6 后,它不会在生产环境中自动启动

ruby-on-rails - 循环遍历 Ruby on Rails 中的对象属性

ruby-on-rails - 在 RubyOnRails 应用程序中生成图形

ruby - 我可以使用 Libsodium 进行 AES-128-ECB 加密吗?

ruby-on-rails - Rails 4 中多对多关系中的急切加载

ruby-on-rails - 为 json 列设置默认值