加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 23:19:00 所属栏目:百科 来源:网络整理
导读:我有一个类方法,我想修改当前由ActiveRecord :: Relation对象抓取的记录.但我不知道如何在类方法中引用当前作用域.自我不这样做. 例: class User ActiveRecord::Base ... def self.modify_those_records #thought implicitly #to_a would be called on curr
我有一个类方法,我想修改当前由ActiveRecord :: Relation对象抓取的记录.但我不知道如何在类方法中引用当前作用域.自我不这样做.

例:

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.然后,我想修改该类方法中的那些记录,然后返回它们.

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

解决方法

你可以使用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

此代码表示您在users表上有一个布尔列is_admin.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读