railsのcontrollerでfindメソッドをDRYに書く

railsのcontrollerの中で各action毎に同様のfindメソッドを呼びたいときがよくあります。
そんなときは以下のようにDRYに書くことができます。

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 :set_post, :only => [:show, :edit, :update, :destroy]

  def show
  end

  def edit
  end

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

  def destroy
    @post.destroy
  end

  private

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

勉強になります。

初めてのRuby

初めてのRuby