I have a rails app with 2 types of users, authenticated and unauthenticated (separated by a email_authenticated:boolean in the database). when I create a user I want it to be unauthenticated but every time I perform any function I want to perform that upon the authenticated list by default. I initially tried to do this by providing a default_scope but found out that this modifies the way the record is saved overrides the default (e.g. the default turns to true rather than false in the example)
# email_authenticated :boolean default(FALSE), not null
class User < ActiveRecord::Base
default_scope { where(email_authenticated: true) }
scope :authenticated, ->{ where(email_authenticated: true) }
scope :unauthenticated, ->{unscoped.where(email_authenticated: false)}
end
does anyone have a suggestion for a way to have a scope only apply on searches, or a smarter way of achieving what I'm going for. I don't want to have to call User.authenticated every time I search if I remove the default scope, similarly I don't want to call User.unauthenticated every time I save on the other hand.
Kind of seems like a hack, but you can do:
class User < ActiveRecord::Base
default_scope { where("email_authenticated = ?", true) }
end
Documented here: http://apidock.com/rails/ActiveRecord/Base/default_scope/class. I just tested it and it works, without the side effect on create.