如何从连接到控制器的过滤器中渲染字符串的一部分
我有一些代码需要在 Rails 1.0 应用程序的多个控制器中使用(出于奇怪的原因,我不能升级到较新的 Rails)。我已将相关代码提取到文件管理器对象中,并使用 around_filter 构造来执行它。
在提取之前,我使用 render_to_string() 方法将渲染的部分的内容获取到字符串中。但是,此方法受到保护,因此我无法从 Filter 对象内访问它。作为解决方法,我尝试将其添加到我的 ApplicationController 中:
def render_to_string(*a)
super(*a)
end
这似乎解决了保护级别问题,但现在我收到错误:
Can only render or redirect once per action
当提取之前没有发生此类错误时。为什么?我应该在这里采取不同的方法吗?
I have some code I need to use in multiple controllers in a rails 1.0 application (I can't, for strange reasons upgrade to a newer rails). I've extracted the relevant code into a filer object, and I'm using the around_filter construct to execute it.
Before the extract, I was using the method render_to_string() to get the contents of a rendered partial into a string. However, this method is protected, so I am unable to access it from within my Filter object. As a workaround, I tried adding this to my ApplicationController:
def render_to_string(*a)
super(*a)
end
this seems to have remedied the protection level issue, but now I get the error:
Can only render or redirect once per action
When no such error occurred before the extraction. Why? Is there a different approach I should take here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,动作将在执行任何过滤器之前调用渲染。由于 render_to_string 通过运行渲染来工作,将结果保存到字符串并实质上撤消渲染,因此会出现“每个操作只能渲染或重定向一次”,因为对渲染的临时调用是在“真正”的渲染调用之后进行的。
我通过在操作结束时简单地调用 after 方法而不是使用 after_filter 或 around_filter 来修复此问题。
我最终还将过滤器移至混合中,以更优雅地避免保护级别问题。
As far as I can tell , an action will call render prior to executing any filters. Since render_to_string works by running render, saving the result to a string and essentially undoing the render, the "Can only render or redirect once per action" comes up because the temporary call to render comes after the "real" call to render.
I fixed this, by simply calling my after method at the end of my action rather than using after_filter or around_filter.
I also ended up moving my filters into a Mix-in, to more elegantly avoid the protection level issue.