Scope in model Rails 3.X


Complex queries in controller make application hard to maintain. Move them into the model as named_scope or scope(Rails 3.X) make the controller simple and the complex find logics are all in models.

Suppose we have in controller,

class JobsController < ApplicationController
     def index
         @published_jobs = Job.find(:all, :conditions => { :status => ‘published’ },
:limit => 20)

So in this example, JobsController uses one complex finder to get published jobs.

There are some problems so far,

  • It is too long which make too difficult to read.
  • If same the code is written anywhere else, then difficult to maintain.
  • If we need to change the logic anytime, then we have to changed it everywhere.

So for this purpose, if we move the code to the model itself then we can use it everywhere.
And if we need any changes in query, then it requires changes in model only.

In model,

class Job < ActiveRecord::Base
     scope :published, :conditions => { :status => ‘published’ },
:limit => 10

In controller,

class JobsController < ApplicationController
    def index
       @published_jobs = Job.published


That’s it.


4 thoughts on “Scope in model Rails 3.X

  1. Sweet blog! I found it while surfing around
    on Yahoo News. Do you have any tips on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there!
    Many thanks


  2. Commonly this includes fibreglass (the most common of
    materials) followed by aluminium, steel, carbon fibre, and others.

    Many Vancouver yacht Rentals would offer yacht charters for
    corporate events Canada and yacht Rentals for
    wedding BC. The Octopus is manned by only forty crew members, some which are most likely ex-Navy Seals.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s