SUPPORT THE SITE WITH A CLICK

Subscribe Rss:

SUPPORT THE SITE WITH A CLICK

Tuesday, November 10, 2009

Named_scope common for all active record models

While i was doing my project in REST Architecture, i used some named_scope in models.Later i saw some of the named_scope like

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

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

1 comment :

  1. Why not?

    ActiveRecord::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

    ReplyDelete