给定一个返回[1,1] [2,3],[5,1]的查询,如何使用该结果?

时间:2011-02-06 04:21:21

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord activemodel

假设:

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

哪个输出:

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

如何使用该结果更新列表。给出结果集1& 3是project_ids,如何迭代结果以更新列表,如:

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

由于

2 个答案:

答案 0 :(得分:1)

不确定我理解,你只想迭代哈希输出html?

<ul>
    <% { 1 => 15, 3 => 10 }.each_pair do |k,v| %>
        <li>Project_id <%= k %>, unread count = <%= v%></li>
    <% end %>
</ul>
编辑:那样的?

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

答案 1 :(得分:1)

首先关闭:您的HTML无效。 li元素位于ulol内,而不是div。您正在寻找的代码是:

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