1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
class PostsController < ApplicationController before_filter :find_post, :only => [:show, :edit, :update, :destroy] def index @posts = Post.find(:all) end def show end def new @post = Post.new end def edit end def create @post = Post.new(params[:post]) if @post.save flash[:notice] = ‘Post was successfully created.‘ redirect_to post_url(@post) else render :action => "new" end end def update if @post.update_attributes(params[:post]) flash[:notice] = ‘Post was successfully updated.‘ redirect_to post_url(@post) else render :action => "edit" end end def destroy @post.destroy redirect_to posts_url end private def find_post @post = Post.find(params[:id]) end end
Refactorings
No refactoring yet !
jamesgolick
September 19, 2007, September 19, 2007 13:32, permalink
Why not use make_resourceful
1 2 3 4 5 6 7
class PostsController < ApplicationController make_resourceful do actions :all end end
Ever noticed how all CRUD methods on each controller starts with the same line: @item = Model.find(params[:id]) ?
Hey! why not use filter so we don’t repeat ourselves ?