Answer the question
In order to leave comments, you need to log in
How to remove (unscoped) scopes from all related ones in Ruby on Rails?
Suppose there are models:
- Subscriber
- Address (subscriber_id)
They are related to each other (has_many and belong_to)
For indirect deletion from the database, each has a deleted field with values true or false.
The default scope is deleted: false
Next, let's say we deleted the Subscriber and its address (deleted: 'true') and wanted to return it back,
for this we do this:
And if we want to extract addresses in this way: - then it doesn't work.
Here is the general code:subscriber = Subscriber.unscoped.find(777)
subscriber.addresses
class Subscriber < ActiveRecord::Base
default_scope { where(deleted: 'false') }
has_many :addresses
end
class Address < ActiveRecord::Base
default_scope { where(deleted: 'false') }
belongs_to :subscriber
end
Answer the question
In order to leave comments, you need to log in
I would advise never to use default_scope, it can bring a lot of problems in the future when scaling, entraining the complexity of the behavior of the model, etc., but at least create a concern with :undeleted, :deleted scopes, and already load objects using the necessary scopes. For the convenience of loading objects in controllers, I can recommend the has_scope gem https://github.com/plataformatec/has_scope where you can set the :undeleted scope by default, and generally control the behavior of all scopes)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question