如何在RoR的视图中正确地重构一个简单的if else逻辑

mmc*_*vi1 2 ruby ruby-on-rails ruby-on-rails-4

我是Rails的新手,我无法解决视图中的重构逻辑问题.假设我有一个简单的Post模型.在索引视图中,如果有帖子,我希望显示特定内容.基本上,如果有任何帖子,则显示此特定内容或其他内容.

这是Posts的index.html.erb视图:

<div class="content">
 <% if @posts.any? %>
 <table>
     <thead>
       <tr>
         <th>Title</th>
         <th>Content</th>
       </tr>
     </thead>
     <tbody>
       <% @posts.each do |post| %>
         <tr>
           <td><%= post.title %></td>
           <td><%= post.content %></td>              
         </tr>
       <% end %>
     </tbody>
   </table>
 <% else %>
 <p>There are no posts!</p>
 <% end %>
</div>
Run Code Online (Sandbox Code Playgroud)

现在,我重构的方式是创建几个助手和部分像这样:

posts_helper.rb(根据if逻辑呈现部分):

module PostsHelper

 def posts_any
  if @posts.any?
    render 'this_content'
  else
    render 'this_other_content'
  end
 end

end
Run Code Online (Sandbox Code Playgroud)

在partials中,我只使用了if else语句中的确切内容.

_this_content.html.erb partial:

<table>
   <thead>
     <tr>
       <th>Title</th>
       <th>Content</th>
     </tr>
   </thead>
   <tbody>
     <% @posts.each do |post| %>
       <tr>
         <td><%= post.title %></td>
         <td><%= post.content %></td>              
       </tr>
     <% end %>
   </tbody>
 </table>
Run Code Online (Sandbox Code Playgroud)

_this_other_content.html.erb部分:

<p>There are no posts!</p>
Run Code Online (Sandbox Code Playgroud)

最后,重构的index.html.erb(可以调用helper方法):

<div class="content">
 <%= posts_any %>
</div>
Run Code Online (Sandbox Code Playgroud)

问题是,我只是不相信这是正确的Rails重构方式.如果你们中的任何一个人能够对此有所了解,我将非常感谢!谢谢!

joe*_*son 6

你做得对,比我认识的人更好.:)

一些小的调整......

我会render从帮助器移动到erb,只需使用帮助器返回正确的渲染内容.

你的erb代码和帮助代码:

<%= posts_any %>

def posts_any
  if @posts.any?
    render 'this_content'
  else
    render 'this_other_content'
  end
end
Run Code Online (Sandbox Code Playgroud)

我建议:

<%= render posts_any %>

def posts_any
  @posts.any? ? 'this_content' : 'this_other_content'
end
Run Code Online (Sandbox Code Playgroud)

接下来,我个人喜欢使用partial来渲染集合.

你:

 <% @posts.each do |post| %>
Run Code Online (Sandbox Code Playgroud)

我建议:

<%= render partial: "post", collection: @posts %>
Run Code Online (Sandbox Code Playgroud)

在下面的评论中,用户kyledecot建议甚至更简洁:

<%= render @posts %>
Run Code Online (Sandbox Code Playgroud)

然后_post.html.erb像这样创建文件:

<tr>
  <td><%= post.title %></td>
  <td><%= post.content %></td>              
</tr>
Run Code Online (Sandbox Code Playgroud)

一些开发人员认为使用partial来渲染集合是过分的,在其他地方不使用partial的情况下.

我个人认为它很有用,当项目有多个编码器时,尤其有用,其中一些编码器可能正在更改表行数据结果.

  • 可以进一步缩短为`<%= render @posts%>` (4认同)