A A

Refactoring Tip: Eliminating Model.find(params[:id]) Duplication

Sun, Dec 7, 2008

Code, Ruby on Rails, Snippets, Tips

In a controller, you’ll commonly have a method that requires you have an instance variable containing the object you’re working with. An example would be the show, edit, update, and destroy methods (REST).

To eliminate having find(params[:id]) in multiple methods, you can use before_filter, like this:

class Admin::PostsController < Admin::ApplicationController
  before_filter :find_post, :only => [:show, :edit, :update, :destroy]
  rescue_from(ActiveRecord::RecordNotFound) { |e| render :text => "<h2>Post not found</h2>" }
 
  def index
    @posts = Post.find(:all)
  end
 
  def show
  end
 
  def new
    @post = Post.new
  end
 
  def create
    @post = Post.new
  end
 
  def edit
  end
 
  def update
  end
 
  def destroy
  end
 
protected 
  def find_post(id = params[:id])
    @post = Post.find(id)
  end
end

(Thanks Jon)
Add me. I'm lonely Why not subscribe to the feed?. If you’re on a mobile device I suggest Viigo

Tags: ,

Leave a Reply