【问题标题】:How to add condition for all where query for an ActiveRecordModel?如何为 ActiveRecord 模型的所有 where 查询添加条件?
【发布时间】:2020-01-01 06:42:07
【问题描述】:

我的 rails 应用程序中有一个用户表,该应用程序在整个应用程序的许多控制器方法中为此模型使用了许多 where 条件。

现在我必须为 where 条件添加一个额外的属性。 有没有办法做到以下几点以及如何做?我可以将自定义where 写入用户模型,而不是将额外属性添加到整个应用程序中使用的所有 where 条件,因此该条件将被预先添加到用户模型的整个应用程序中的where

我找到了哪里的来源

def where(opts = :chain, *rest)
 if :chain == opts
  WhereChain.new(spawn)
 elsif opts.blank?
  self
 else
  spawn.where!(opts, *rest)
 end
end

我现在在控制器方法中的 where 条件:

User.where(:status => true, :country => "IN")

此条件和类似条件在应用程序中的许多方法中使用,我想获得没有:deactivated的用户。

我可以对所有 where 条件进行更改,例如

User.where(:status => true, :country => "IN", :deactivated => false)

相反,我想写一个自定义,其中预检查:deactivated => false

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    默认范围:

    class User < ActiveRecord::Base
      default_scope -> { where(deactivated: false) }
    end
    

    您可以使用default_scope

    现在,无论何时查询 User,都会自动附加默认范围查询。

    更多default_scope详情请参考: https://api.rubyonrails.org/classes/ActiveRecord/Scoping/Default/ClassMethods.html#method-i-default_scope

    如果存在阻止您使用 default_scope 的用例,那么您可以使用自定义范围或取消默认范围的范围。

    取消范围:

    如果您想删除默认范围,您可以取消Project 模型中的范围。

    belongs_to :user, -&gt;{ unscope(where: :deactivated) }

    或者您可以获取所有用户,然后取消范围 project.users.unscoped

    自定义范围:

    class User < ActiveRecord::Base
      scope :deactivated, ->(deactivated = false) { where(deactivated: deactivated) }
    end
    

    现在,要使用该范围,您可以这样查询:

    User.deactivated.where(:status => true, :country => "IN")
    

    供参考: https://api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/ClassMethods.html#method-i-scope

    【讨论】:

    • 我不能使用default_scope,因为假设一个项目属于一个停用的用户。如果我们给project.user它不会显示结果。
    • 已更新答案,请查收
    • 对于这个解决方案,我还需要对我的方法中存在条件的所有旧的地方进行更改
    • 是的,据我所知,只有这两个选项。
    • 添加belongs_to :user, -&gt;{ unscope(where: :deactivated) }将不属于协会范围,感谢您的回答,请更新以便我接受答案
    猜你喜欢
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 2018-06-18
    • 2014-07-09
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多