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

Time:11-01

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>

CodePudding user response:

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.

  • Related