Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Scopes in rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 56
    Comment on it

    A unanimous definition of  a scope in rails can be termed as a succinct way of creating database queries. We define a scope in a Model class in the purview of MVC architecture.

    It's syntax goes like: scope(name, body, &block) .

    To give a basic feeling of what does a scope do ,consider the following example.But remember we use scopes for much complex functionalities.

    class Blog < ActiveRecord::Base
      scope :current_status, -> status { where(status: status) }
      scope :latest, -> { order("blogs.created_at ASC") }
    end

    here ,we have two scopes named current_status and latest ,the first one simply assigns a status for a particular blog and the second scope namely latest sorts the entire blogs in the ascending order of their creation time.

    Blog.current_status('pending').recent
    # SELECT "blogs".* FROM "blogs" WHERE "blogs"."status" = 'pending' 
    #   ORDER BY blogs.created_at ASC

    The same task can be achieved using class-methods instead of using scopes :

    class Blog < ActiveRecord::Base
      def self.current_status(status)
        where(status: status)
      end
      
      def self.latest
        order("blogs.created_at ASC")
      end
    end

    A call to a scope returns an ActiveRecord::Relation object that allows for further chaining with other scopes.

    Thanks.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: