4: Move Find Into Model 

(view original Railscast)

Other translations: It Es Fr

Below we have a Task model and we’re perfoming a find on that model.

class TaskController < ApplicationController
  def index
    @tasks = Task.find_all_by_complete_(false, :order => "created_at DESC")

If the find is being performed several times throughout the application then there will be duplication. One way to remove this duplication is to move the find into the model, which would allow us to call

@tasks = Task.find_incomplete

in the controller. To do this we’ll need to create a new method in the model. The method has to be a class method so must start with self.

class Task < ActiveRecord::Base
  belongs_to :project
  def self.find_incomplete
    find_all_by_complete_(false, :order => "created_at DESC")

There’s no need to specify Task in the find line as the find is already scoped inside the Task class. Now you can call Task.find_incomplete whenever you need to perform that find. This will even work in associations so that you can find Project’s incomplete tasks like this:

class ProjectsController < ApplicationController
    def show
        @project = Project.find(params[:id])
        @tasks = @project.tasks.find_incomplete