简体   繁体   English

使用Rails过滤模型上的所有搜索

[英]Filtering all the searches on a model with ruby on rails

Im dealing with a situation with a refactor on a running app with Ruby on Rails. 我正在使用Ruby on Rails在运行的应用程序上处理重构问题。

On the app, I have a user that can have their profile active/inactive. 在该应用程序上,我有一个可以使个人资料处于活动状态/非活动状态的用户。

On the User too, I have his date of birth. 在用户上,我也有他的生日。 And for all the users that are less then 13 years old, the accounts need to behavior like "inactive". 对于所有小于13岁的用户,帐户都需要具有“无效”之类的行为。

I just added a is_active boolean property to the User model. 我刚刚向用户模型添加了一个is_active布尔属性。

The question is: I dont want to refactor ALL my queries on Users on the app, adding 问题是:我不想在应用程序上重构对用户的所有查询,添加

User.where(is_active: true).where(age > 13)  

By hand on all the models 手动在所有型号上

I want to use some other technique, maybe a callback function on the User model, or in the controller. 我想使用其他技术,可能是用户模型或控制器中的回调函数。

What do you sugest? 你什么意思?

default_scope is what you need if you don't want to change queries already written but want to add the default condition 如果您不想更改已编写的查询但想添加默认条件,则需要default_scope

class User < ActiveRecord::Base
  default_scope { where(is_active: true).where("age > 13") }
end

NOTE : default_scope is not suggested to use so do your research accordingly 注意 :建议不要使用default_scope ,因此请做相应的研究

Solution 2: 解决方案2:

You will have to add the scope once in all the places where you are querying on the users table 您将必须在用户表上所有要查询的地方添加一次范围

class User < ActiveRecord::Base
  scope :active, -> { where(is_active: true).where("age > 13") }
end

and use it 并使用它

User.active.where(...)

you might have to handle the above conditions while joining the models 您可能需要在加入模型时处理上述条件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM