【译】DRY Controller

Sunday, July 25, 2010

原文:http://rails-bestpractices.com/posts/23-dry-controller

对于增删改查的资源,我们通常重复的编写那9个action,可以使用inherited_sources插件来避免大量的重复代码

重构前...

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

重构后...

class PostsController < InheritedResources::Base
  # magic!! nothing here!
end

使用
inherited_resources这个
gem,你以避免DRY, 控制器变得干干净净

This entry was tagged Rails and Best-Practices

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top