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

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 => "

Post not found

" } def index @posts = Post.find(:all) end def show end def new @post = end def create @post = 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)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>