Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在RoR视图中正确重构简单的if-else逻辑_Ruby On Rails_Ruby_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 如何在RoR视图中正确重构简单的if-else逻辑

Ruby on rails 如何在RoR视图中正确重构简单的if-else逻辑,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我是Rails的新手,我很难从视图中重构逻辑。假设我有一个简单的Post模型。在“索引”视图中,如果有帖子或没有帖子,我希望显示特定的内容。基本上,如果有任何帖子,请显示此特定内容或其他内容 以下是我的index.html.erb帖子视图: <div class="content"> <% if @posts.any? %> <table> <thead> <tr> <th>Ti

我是Rails的新手,我很难从视图中重构逻辑。假设我有一个简单的Post模型。在“索引”视图中,如果有帖子或没有帖子,我希望显示特定的内容。基本上,如果有任何帖子,请显示此特定内容或其他内容

以下是我的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>
在部分中,我只使用了if-else语句中的确切内容

_此_content.html.erb部分:

<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>
<p>There are no posts!</p>

标题
内容
_此_other_content.html.erb部分:

<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>
<p>There are no posts!</p>
没有帖子

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


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

你做得对,比我认识的许多人都好。:)

一些小的调整

我会将
渲染
从辅助对象移动到erb,然后使用辅助对象返回要渲染的内容的正确名称

您的雇员再培训局代码和助手代码:

<%= posts_any %>

def posts_any
  if @posts.any?
    render 'this_content'
  else
    render 'this_other_content'
  end
end
一些开发人员认为,如果在其他任何地方都不使用分部,那么使用分部来呈现集合就太过分了


我个人认为这是很有帮助的,尤其是当一个项目有多个程序员时,其中一些人可能正在更改表行数据结果。

可以进一步缩短为
@kyledecot极好的一点。“我再补充一句。”乔尔帕克汉德森谢谢你的解释,好心的先生
<%= render posts_any %>

def posts_any
  @posts.any? ? 'this_content' : 'this_other_content'
end
 <% @posts.each do |post| %>
<%= render partial: "post", collection: @posts %>
<%= render @posts %>
<tr>
  <td><%= post.title %></td>
  <td><%= post.content %></td>              
</tr>