0

I like to dry my controllers by placing reoccurring code in before and after filters. In my current project, every action has the same respond_to block:

respond_to do |wants|
  wants.html
  wants.js { render :layout => "transition" }
end

I placed this in an after_filter like so:

after_filter :respond_to_html_or_transition

But it leads to this error:

Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

This happens even when there is no explicit respond_to or redirect within the action. I'm assuming this happens because Rails (for lack of an explicit respond_to call) makes an educated guess and creates its own respond_to before the after_filter. If that's the case, is there any way for me to keep Rails from doing that and instead use the block in the after_filter?

4

1 回答 1

0

使用 after_filter 无法完成您要完成的工作。after 过滤器处理已经渲染的动作。此时,渲染已经完成(显式或隐式渲染),因此调用渲染将导致双重调用。

您可以提取方法中的代码逻辑并调用该方法。另一种选择是使所有动作成为单个动作的别名,假设动作的主体可以由单个方法处理。

最后但并非最不重要的一点是,您可以编写自定义操作响应器并替换默认的控制器设置

self.responder = CustomActionResponder
于 2013-05-02T16:31:39.047 回答