1

我在我的 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

我可以对所有条件进行更改

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

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

4

1 回答 1

3

默认范围:

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

于 2019-08-28T05:58:21.630 回答