我的 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
我现在在控制器方法中的位置条件:
User.where(:status => true, :country => "IN")
这个条件和类似的条件在应用程序中的许多方法中使用,我想得到没有:deactivated
的用户。
我可以对所有条件进行更改,例如
User.where(:status => true, :country => "IN", :deactivated => false)
相反,我想写一个自定义,其中预检查:deactivated => false
默认作用域:
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, ->{ 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