小编mmc*_*vi1的帖子

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

我是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><%= …
Run Code Online (Sandbox Code Playgroud)

ruby ruby-on-rails ruby-on-rails-4

2
推荐指数
1
解决办法
998
查看次数

标签 统计

ruby ×1

ruby-on-rails ×1

ruby-on-rails-4 ×1