Reputation: 355
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?
Upvotes: 0
Views: 177
Reputation: 23671
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
Upvotes: 1