Hi how to build a named_scope which will be common for all models.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With