簡體   English   中英

紅寶石如何讀取哈希

[英]ruby how to read hash

控制器代碼:

def index
  @folders = Folder.where(parent_id: 0, user_id: current_user)
  @subfolders = Hash.new()
  @folders.each_with_index do |folder, index|
    @subfolders[folder.id] = { folder.id => Folder.where(parent_id: folder.id) }
  end
end

視圖:

<% @folders.each_with_index do |folder, index| %>
  <td><%= folder.name %></td><br />
  @subfolders[index].name
<% end %>

@subfolders [1] .to_s對象本身返回以下結果:

{1=>#<ActiveRecord::Relation [#<Folder id: 2, name: "tt", user_id: 1, created_at: "2014-06-21 19:29:32", updated_at: "2014-06-21 19:29:32", parent_id: 1>]>}

我的問題是,如何閱讀此@subfolders哈希? 我想在顯示父項后顯示子文件夾...請幫助

以下似乎是一種更有效的解決方案,因為它運行2個查詢,而您的查詢生成n + 1

ids = Folder.where(parent_id: 0, user_id: current_user).pluck(:id)
@subfolders = Folder.where(parent_id: ids).group_by(:parent_id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM