简体   繁体   中英

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.

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".

I just added a is_active boolean property to the User model.

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

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

Solution 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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