Banning a model

Go To StackoverFlow.com

1

I have several models that belong_to :status.

Statuses are:

  • Active
  • Hidden
  • Banned

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.

2012-04-04 03:49
by Kyle Macey


2

You need to define some scopes

default_scope joins(:status).where(:status => {:state => :active})
scope :hidden, unscoped.joins(:status).where(:status => {:state => :hidden})
2012-04-04 04:04
by MikDiet
Wow thanks! I might have to try it tomorrow as the wife broke her laptop and has commandeered my machine to watch Netflix - Kyle Macey 2012-04-04 05:22
Beautiful, thanks a lot - Kyle Macey 2012-04-04 22:16
Quick note, using the join made the model read-only, so I just used where(:status_id => 1) It was default_scope that saved my life, thank - Kyle Macey 2012-04-06 19:42
Ads