Default_scope to continue

ActiveRecord has a default_scope class method for specifying the default scope. for instance

 class User < ActiveRecord::Base default_scope where(:deleted => false) end User.all # => SELECT * FROM users WHERE deleted = 0; 

How to do it in Sequel::Model ?

EDIT:

After some googling, I found some useful information.

 class User < Sequel::Model # Define some "scopes" (filters on the dataset) dataset_module do def existing filter(deleted: false) end def active filter(disabled: false) end end # This is the equivalent to a default_scope. Set one of the datasets # as the default dataset for this model. set_dataset(self.active) end 

The generated query is as follows:

 User.all # => SELECT * FROM `users` WHERE (`deleted` IS FALSE) 

By the way : the equivalent of unscoped is unfiltered :

 User.unfiltered.all # => SELECT * FROM `users` 

But , there is one problem. If you try to update a user that you received from an unfiltered dataset, he tries to update the user using this dataset.

 User.create(disabled: true, deleted: true) User.all # => [] u = User.unfiltered.first # => Given user u.disabled = false u.save # => UPDATE users SET ... WHERE (disabled IS FALSE AND id = 1) # => Sequel::NoExistingObject: Attempt to update object did not result in a single row modification 

So, I returned to the beginning. Any workaround for this?

+6
source share
1 answer

The best workaround is to fix the problem without having a default scope. In most cases, the default area is a bad idea. If you want most of your queries to use the scope, then apply the scope manually in these queries, do not use the default scope and try to cancel the scope in other queries. The default scope makes sense only if all of your queries use this scope.

You can also handle this by subclassing (user does not have scope, ActiveUser <User in scope). However, I believe that a clear approach works better.

All of the above, if you really want to use the default scope, there may be a problem updating the model instance outside the default model:

 User.instance_dataset.unfiltered! 
+5
source

Source: https://habr.com/ru/post/921406/


All Articles