Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use common named_scope for all ActiveRecord models

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

like image 949
Gen Avatar asked Dec 22 '22 08:12

Gen


2 Answers

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.

Update:

scope is used in Rails > 3 and named_scope was used in previous versions.

like image 178
Casper Fabricius Avatar answered Mar 09 '23 00:03

Casper Fabricius


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.

like image 44
James A. Rosen Avatar answered Mar 09 '23 00:03

James A. Rosen