Friday, 25 May 2007

Scope out your models

Just found a nitfy plugin called AutoScope. It lets you define scopes for a model. For example:

class User < ActiveRecord::Base
   auto_scope \
       :fresh => {:find => {:conditions => ['activated_at IS NULL AND destroyed_at IS NULL']},
       :active => {:find => {:conditions => ['activated_at IS NOT NULL AND destroyed_at IS NULL']}},
       :archived => {:find => {:conditions => ['destroyed_at IS NOT NULL']}}
end

These set up some scoped methods

 new_count = User.fresh.count
 old_users = User.archived.find(:all)
 User.fresh.find(:all).each {|u| u.update_attribute(:activated_at, Time.now.to_utc)} 

I've found these great for filtering collection views that group users distinctly, but span across multiple columns.


    def filter_users
      return default_search unless params[:user_scope]
      scope = params[:user_scope].to_sym 
      case scope
      when :fresh, :active, :archived
        # scopes we recognise
        users = User.send(scope).find(:all)
      else
        users = User.find(:all)
      end
      users
    end

Do note, though, to be careful what to name your scopes. I started out by calling my "fresh" scope "new". Unfortunately this overwrote the "new" function on my User model... not a Good Thing.

No comments: