In ActiveRecord there is a default_scope
class method to specify a default scope. For example
class User < ActiveRecord::Base
default_scope where(:deleted => false)
end
User.all # => SELECT * FROM users WHERE deleted = 0;
How can I do this in Sequel::Model
?
EDIT:
After some googling I eventually 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 then looks like this:
User.all # => SELECT * FROM `users` WHERE (`deleted` IS FALSE)
By the way: The equivalent to unscoped
is unfiltered
:
User.unfiltered.all # => SELECT * FROM `users`
But, there is one problem. If you try to update a user you got from an unfiltered dataset, it tries to update the user using the given 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 am back at the beginning. Any workaround for this?