DRY Controller (debate)
24 Jul 2010
Before Refactor
class PostsController < Applicationcontroller
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
end
def create
@post.create(params[:post])
redirect_to post_path(@post)
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
@post.update_attributes(params[:post])
redirect_to post_path(@post)
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to posts_path
end
end
For CRUD resources, you always write the 7 actions with duplicated codes.
After Refactor
class PostsController < InheritedResources::Base
# magic!! nothing here!
end
Using inherited_resources gem, you can avoid repeating yourself, the controller files are really clean.
Updated: thanks @carlosantoniodasilva
Updated: Add debate
Tags controller plugin