How to use common named_scope for all ActiveRecord models

Hi, how to create a named_scope that will be distributed to all models.

+3
source share
3 answers

I do this 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 would recommend using base.table_nametables to classify columns when referenced in these named areas, as shown in the example. Otherwise, you will encounter problems with ambiguous references when combining these named areas with other areas that are combined into other tables.

Update:

scope Rails > 3 named_scope .

+8

Thoughtbot Pacecar, . , . - , .

+1

For the Rails4 project, I achieved this by extending the ActiveRecord::Baseclass to which all Rails models inherit in the initializer (approach to fixing the monkey, beware)

# in /config/initializers/shared_scope_initializer.rb
module SharedScopes
  extend ActiveSupport::Concern

  module ClassMethods
    def named_scope
      return where(attribute: value) # query here
    end
  end
end

ActiveRecord::Base.send(:include, SharedScopes)
0
source

Source: https://habr.com/ru/post/1722096/


All Articles