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
勉強になります。
- 作者: Yugui
- 出版社/メーカー: オライリージャパン
- 発売日: 2008/06/26
- メディア: 大型本
- 購入: 27人 クリック: 644回
- この商品を含むブログ (246件) を見る