named_scope :limit, lambda {|limit| {:limit => limit}}
Then after a long search in Google.I started created a module in lib folder, and i had my common named_scope.Then i started calling the module in my models.
module CommonScopes
def self.included(base)
base.class_eval do
named_scope :limit, lambda {|limit| {:limit => limit}}
named_scope :include_user,:include=>:user
end
end
end
def self.included(base)
base.class_eval do
named_scope :limit, lambda {|limit| {:limit => limit}}
named_scope :include_user,:include=>:user
end
end
end
ActiveRecord models
class Forum < ActiveRecord::Base
has_many:topics, :dependent=>:delete_all
has_many:posts, :through=>:topics
validates_presence_of :name
validates_length_of :name, :maximum => 255
validates_length_of :description, :maximum => 1000
include CommonScopes
end
Please refer this article for knowing the difference between include vs extend
has_many:posts, :through=>:topics
validates_presence_of :name
validates_length_of :name, :maximum => 255
validates_length_of :description, :maximum => 1000
include CommonScopes
end
Why not?
ReplyDeleteActiveRecord::Base.named_scope :limit, lambda {|limit| {:limit => limit}}
in one of the initializers? It saves from "include CommonScopes" in every model class. More DRY? or am I missing something.
and a bit more suitable code can be,
lambda {|*limit| {:limit => limit.flatten.first || 10}}
it saves the burden of parameter on every call.
"10" can by anything that suits the application.
Call it as ...
MyModel.limit # gets 10 rows
MyModel.limit(5) # gets just 5