views:

229

answers:

3

Hi how to build a named_scope which will be common for all models.

+6  A: 

I do that by putting this code in lib/has_common_named_scopes.rb:

module HasCommonNamedScopes
  def self.included(base)
    base.class_eval {
      # Named scopes
      named_scope :newest, :order => "#{base.table_name}.created_at DESC"
      named_scope :freshest, :order => "#{base.table_name}.updated_at DESC"
      named_scope :limit, lambda { |limit| {:limit => limit} }
    }
  end
end

and then include the module in each model where I need them:

class MyModel < ActiveRecord::Base
  include HasCommonNamedScopes

I'd recommend that you use base.table_name to qualify the table when referring to columns in these named scopes like I do in the example. Otherwise you run into problems with ambiguous references when you combine these named scopes with other scopes that join in other tables.

Casper Fabricius
+1  A: 

There's also Thoughtbot's Pacecar, which adds a bunch of very common named scopes to every model. It might come with what you're looking for. If you need something custom, though, Casper Fabricius has the right idea.

James A. Rosen
A: 

Thanks for your suggestions

Gen