I have several models that belong_to :status
.
Statuses are:
I have scopes set up for each of the statuses, and they apply to users and several other content models, but let's take User
for example.
Out of habit, I write User.find(15)
or User.all
or User.last(5)
or @category.users
I don't think there should be any reason to change that. In fact, call me selfish, but I don't want to change that. I feel like I should be able to handle this sort of task at a higher level, and avoid having to retype over and over again:
User.active.where(...)
User.active
User.active.last(5)
@category.users.active
That just seems unconventional. Unfortunately, these models are used throughout many instances, so I would like a way, maybe at the model level, to prescreen for banned or hidden models. For example, removing banned instances from the all
scope, but as well as scopes like "last" or when the model is queried in general. Or if an instance is called specifically that falls withing the banned or hidden scope, it raises a record not found. I'd still like to be able to access these instances through their individual scopes (eg User.banned
or User.hidden
) but I'd rather that be the extra typing, rather than the queries that are most commonly used.
You need to define some scopes
default_scope joins(:status).where(:status => {:state => :active})
scope :hidden, unscoped.joins(:status).where(:status => {:state => :hidden})
where(:status_id => 1)
It was default_scope
that saved my life, thank - Kyle Macey 2012-04-06 19:42