简体   繁体   中英

Ruby on Rails - Get first n number of elements from array with condition

In my Rails view template, the @comments is an array of hashes. I just need to show the first three comments that meet this condition <% if post["id"] === comment["postId"] %>. Right now it's showing all of them.

 <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>

When you only want to show the first 3 comments that match a certain condition then I would do this:

<% 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>

You might load the @comments with the condition in the controller to make the view easier to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM