在我的 Rails 視圖模板中,@comments 是一個哈希陣列。我只需要顯示滿足此條件的前三個評論 <% if post["id"] === comment["postId"] %>。現在它顯示了所有這些。
<tbody>
<% @posts.each do |post| %>
<tr>
<% @users.each do |user| %>
<% if post["userId"] === user["id"] %>
<td> <%= user["name"] %></td>
<% end %>
<% end %>
<td><%= post["title"] %></td>
<td><%= post["body"] %></td>
<% comments_total = 0 %>
<% @comments.each do |comment| %>
<% if post["id"] === comment["postId"] %>
<td><%= comment["body"] %></td>
<% comments_total = 1 %>
<% end %>
<% end %>
<td><%= comments_total %></td>
<% end %>
</tr>
</tbody>
uj5u.com熱心網友回復:
當您只想顯示符合特定條件的前 3 條評論時,我會這樣做:
<% matching_comments = @comments.select { |comment| comment["postId"] == post["id"] } %>
<% matching_comments.first(3).each do |comment| %>
<td><%= comment["body"] %></td>
<% end %>
<td><%= matching_comments.size %></td>
您可以在控制器中加載帶有條件的@comments 以使視圖更易于閱讀。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/342919.html
標籤:红宝石轨道 红宝石 红宝石 ruby-on-rails-5
