在一个无关紧要的情况下,我正在使用Ruby on Rails编写一个博客应用程序。我的PostsController
包含一些代码,可确保登录的用户只能编辑或删除他们自己的帖子。Rails:保持用户欺骗检查DRY
我尝试了保理这个代码到一个私有方法与闪光灯消息显示一个说法,但我这样做,并通过编辑另一位作者的帖子测试它的时候,我得到了一个ActionController::DoubleRenderError
- “只能渲染或重定向每次行动一次“。
如何保存这些检查DRY?明显的方法是使用before过滤器,但destroy
方法需要显示不同的闪存。
下面是相关的控制器代码:
before_filter :find_post_by_slug!, :only => [:edit, :show]
def edit
# FIXME Refactor this into a separate method
if @post.user != current_user
flash[:notice] = "You cannot edit another author’s posts."
redirect_to root_path and return
end
...
end
def update
@post = Post.find(params[:id])
# FIXME Refactor this into a separate method
if @post.user != current_user
flash[:notice] = "You cannot edit another author’s posts."
redirect_to root_path and return
end
...
end
def destroy
@post = Post.find_by_slug(params[:slug])
# FIXME Refactor this into a separate method
if @post.user != current_user
flash[:notice] = "You cannot delete another author’s posts."
redirect_to root_path and return
end
...
end
private
def find_post_by_slug!
slug = params[:slug]
@post = Post.find_by_slug(slug) if slug
raise ActiveRecord::RecordNotFound if @post.nil?
end
不要在验证之前进行查询! – 2009-05-23 16:18:13