【发布时间】:2013-09-21 08:29:40
【问题描述】:
我正在使用 Ruby on Rails 3.2.13,我想在控制器和视图中干燥(不要重复自己)我的代码。也就是此时……
...在我的控制器中,我有:
# ArticlesController
def index
@articles = ...
...
case ...
when ... then render(:partial => 'partial_for_index', :object => @articles, :as => 'articles', ...)
else render :index
end
end
def show
@article = ...
...
case ...
when ... then render(:partial => 'partial_for_show', :object => @article, :as => 'article', ...)
else render :show
end
end
...在我的助手中我有:
# ArticlesHelper
def render_partial_for_index(articles, ...)
articles.map { |article| render_partial_for_show(article, ...) }.join('').html_safe
end
def render_partial_for_show(article, ...)
render(:partial => 'partial_for_show', :object => article, :as => 'article', ...)
end
...在我看来,我有:
# articles/_partial_for_index.html.erb
<%= render_partial_for_index(@articles, ...) %>
# articles/_partial_for_show.html.erb
<%= article.title %> created at <%= article.created_at %>
为了干燥我的代码,我想直接在控制器中使用辅助方法(注意:我知道这种方法破坏了 MVC 模式,但这只是我的目标和应该做的一个例子使问题更容易理解),这样:
# ArticlesController
include ArticlesHelper
def index
@articles = ...
...
case ...
when ... then render_partial_for_index(@articles, ...)
else render :index
end
end
def show
@article = ...
...
case ...
when ... then render_partial_for_show(@article, ...)
else render :show
end
end
这样我可以删除_partial_for_index.html.erb 视图文件,因为它不再被使用,并且代码在整个应用程序中DRYed 和一致。然而,虽然控制器 show 操作按预期工作,但控制器 index 操作却没有,因为我收到了 DoubleRenderError 错误,因为多个 render 方法在 render_partial_for_index 辅助方法中运行。
简而言之,我想使用尽可能少的语句进行渲染。我如何/应该干燥我的代码以达到我的目标?也就是说,我怎样才能以正确的方式在视图和控制器中保持render_partial_for_index 和render_partial_for_show 方法的可用性?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 rendering dry