Given a query that returns [1, 1] [2, 3], [5,1], How to you use that result?

103 Views Asked by At

Given:

class ThreadParticipations
  scope :unread, lambda{ |user| where(:user_id => user.id, :read => false) }
end

ThreadParticipations
  .unread(current_user)
  .includes(:thread => :project)
  .group('projects.id')
  .count('threads.id')

Which outputs:

 => { 1 => 15, 3 => 10 }

How do I use that result to update my list. Given in the result set 1 & 3 are project_ids, how can I iterate through that results to update a list like:

# iterates over @projects
<div>
 <li>Project_id 1, unread count = 15</li>
 <li>Project_id 2, unread count = 0</li>
 <li>Project_id 3, unread count = 10</li>
 <li>Project_id 4, unread count = 0</li>
 <li>Project_id 5, unread count = 0</li>
</div>

Thanks

2

There are 2 best solutions below

4
On BEST ANSWER

Not sure I understand, you just want to iterate on the hash to output the html?

<ul>
    <% { 1 => 15, 3 => 10 }.each_pair do |k,v| %>
        <li>Project_id <%= k %>, unread count = <%= v%></li>
    <% end %>
</ul>

edit: like that?

<ul>
    <% [[1,1], [2, 3], [3, 15]].each do |project_id, unread_count| %>
        <li>Project_id <%= project_id %>, unread count = <%= unread_count %></li>
    <% end %>
</ul>
0
On

First off: Your HTML is invalid. li elements go inside ul's or ol's, not div's. The code you're looking for is:

<ul>
  <% hash.each do |project_id, unread_count| %>
    <li>Project_id <%= project_id %>, unread count = <%= unread_count %></li>
  <% end %>
</ul>