I'm trying to set a default scope so that Users where notified: true
are soft-deleted. notified
is a boolean data column.
This is what I've tried:
class User < ActiveRecord::Base
default_scope { where('notified != ?', true) }
#...
end
But this way, no users appear in any scope. ie - all the users appear to be soft-deleted, even the ones with notified: false
or notified: nil
. What's wrong with my scope?
I recommend using boolean values the database understands. In this case you want to see users that have a notified that is not true, so I'd user:
default_scope { where('notified IS NOT TRUE') }
That way users will only appear in other scopes if their boolean database values is FALSE
or NULL
.
Note: default scopes are actually considered a code smell... because they're a bit magic and hide away what you really mean when you fetch out users. You might want to instead create an active
and inactive
scope and specify them explicitly in your code eg:
scope :active ->{ where('notified IS NOT TRUE') }
scope :inactive ->{ where('notified IS TRUE') }
# in your controller
def index
@users = User.active.all
end