0

我正在使用 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

4

1 回答 1

1

实际上我不喜欢你的控制器,因为它混合了应该属于视图的逻辑,而 render_blah 方法使事情变得不必要地复杂。

我更喜欢这种风格:

# ArticlesController
def index
  @articles = ...
end

def show
  @article  = ...
end

# views/articles/index.html.erb
<% @articles.each do |article| %>
  <%= render partial: 'article', locals: {article: article}
<% end %>

# views/articles/show.html.erb
<%= render partial: 'article', locals: {article: @article}

# views/articles/_article.html.erb
<%= article.title %>
<%= article.body  %>
# blah blah

一样的效果。干燥机代码。更清晰的逻辑。不需要帮手。

于 2013-09-21T08:54:08.860 回答