Skip to content
Richard Huang edited this page Aug 15, 2010 · 3 revisions

Please go to http://rails-bestpractices.com/posts/22-use-before_filter

Before:


class PostsController < ApplicationController

  def show
    @post = current_user.posts.find(params[:id])
  end

  def edit
    @post = current_user.posts.find(params[:id])
  end

  def update
    @post = current_user.posts.find(params[:id])
    @post.update_attributes(params[:post])
  end

  def destroy
    @post = current_user.posts.find(params[:id])
    @post.destroy
  end

end

After:


class PostsController < ApplicationController
  before_filter :find_post, :only => [:show, :edit, :update, :destroy]

  def update
    @post.update_attributes(params[:post])
  end

  def destroy
    @post.destroy
  end

  protected

  def find_post
    @post = current_user.posts.find(params[:id])
  end

end