Topic: How to define general scopes

I have numerous models in my project, and several want sorting by name, several by date. Clearly doing this with scopes is the way to go:

class MyClass < ActiveRecord::Base 
  scope :name_ordered, -> { order 'name ASC' }

  ...
end

Rather than define them in half a dozen different classes, so much better to define them once in ActiveRecord::Base, that is the DRY way, afterall.

class ActiveRecord::Base
  scope :name_ordered, -> { order 'name ASC' }
end

class MyClass < ActiveRecord::Base
  ...
end

Only it does not work, and I just get this error each time it tries to use the scope:

NoMethodError: undefined method `abstract_class?' for Object:Class

Is there a way around this?

Re: How to define general scopes

The solution seems to be to explicitly create the methods in ActiveRecord::Base, rather than using scope to create it for you.

class ActiveRecord::Base
  def self.name_ordered
    order('name ASC')
  end
end

Re: How to define general scopes

Thanks for sharing.It will help me ahead.

Drinkdings