0

Controller code:

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

View:

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

the @subfolders[1].to_s object itself returns this result:

{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>]>}

My question is , how to read this @subfolders Hash in view ? I want to display subfolder after parent is displayed... Please help

bjhaid
  • 9,592
  • 2
  • 37
  • 47
user3581552
  • 85
  • 1
  • 1
  • 7
  • I think `@subfolders[folder.id]` will be `@subfolders[index]` Right ? – Arup Rakshit Jul 07 '14 at 17:12
  • `@subfolders[folder.id][folder.id]` will do. but why you need such strange chaining. – maximus ツ Jul 07 '14 at 17:22
  • Yes, thats working, but you right actually. The thing is, once i read all the parent folders, i need collection to store its subfolders, thats why i decided to use hases. If you have any suggestions please let me know? Is it possible to rewrite using arrays ? – user3581552 Jul 07 '14 at 17:29

1 Answers1

1

The below is seems to be a more efficient solution to your problem as it runs 2 queries while yours generates an n + 1

ids = Folder.where(parent_id: 0, user_id: current_user).pluck(:id)
@subfolders = Folder.where(parent_id: ids).group_by(:parent_id)
Community
  • 1
  • 1
bjhaid
  • 9,592
  • 2
  • 37
  • 47