在一個無關緊要的情況下,我正在使用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