【译】使用before_filter

Sunday, July 25, 2010

原文:http://rails-bestpractices.com/posts/22-use-before_filter

不要在控制器中重复你的对象finder, 使用before_filter避免相同的代码

丑陋的...

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

在这个例子中, 所有方法的第一行都是重复, 我们讨厌重复的代码,所以需要用before_filter来避免这个问题

重构...

```ruby
class PostsController < ApplicationController
before_filter :find_post, :only => [:show, :edit, :update, :destroy]

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

def destroy
@post.destroy
end

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

我们看到, 所有的post finder都从action中移走了, 只在before_filter中, 记住不要重复你自己!~

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