形成这个多维数组的正确方法是什么?

时间:2013-12-05 17:40:03

标签: ruby-on-rails ruby

我正在尝试执行一系列请求,这些请求将按照每个位置将位于顶层的方式组织给定日期范围内的结果,并包含具有每组结果的另一个数组。以下是我到目前为止的情况:

locations = Location.all
@requests = []
locations.each do |location|
    request = PurchaseRequest.where('created_at >= ? AND created_at <= ? AND location_id = ?', params[:start_date], params[:end_date], location.id).order(:location_id)
    @requests.push(location => request)
end

我在视图中的理想(非工作)实现看起来像:

<ul>
<% @requests.each do |location| %>
    <li>location[0].name</li>
    <ul>
        <% location[1].each do |request| %>
            <li>request.name</li>
        <% end %>
    </ul>
<% end %>
</ul>

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

@requests = {}
Location.all.each do |location|
  @requests[location.name] = PurchaseRequest.where('created_at >= ? AND created_at <= ? AND location_id = ?', params[:start_date], params[:end_date], location.id).order(:location_id)
end

<ul>
  <% @requests.each do |location_name, request_list| %>
    <li><%= location_name %></li>
    <ul>
      <% request_list.each do |request| %>
        <li><%= request.name %></li>
      <% end %>
    </ul>
  <% end %>
</ul>

@requests成为哈希,密钥是位置名称,值是购买请求。