How to use common named_scope for all ActiveRecord models
Hi how to build a named_scope which will be common for all mod开发者_如何学编程els.
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.
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.
For a Rails4 project I achieved this by extending ActiveRecord::Base
, the class all Rails models inherit from, in an initializer (monkey patching approach, 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)
精彩评论