Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ruby如何读取哈希_Ruby On Rails_Ruby_Algorithm_Loops - Fatal编程技术网

Ruby on rails ruby如何读取哈希

Ruby on rails ruby如何读取哈希,ruby-on-rails,ruby,algorithm,loops,Ruby On Rails,Ruby,Algorithm,Loops,控制器代码: 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 视图

控制器代码:

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>]>}
{1=>#}

我的问题是,如何在视图中读取@subfolders散列?我想在显示父文件夹后显示子文件夹。。。请帮助

以下内容似乎是解决您问题的更有效的方法,因为它运行2个查询,而您的查询生成一个


我想
@subfolders[folder.id]
将是
@subfolders[index]
对吧?
@subfolders[folder.id][folder.id]
就可以了。但是为什么你需要这么奇怪的锁链。是的,这是有效的,但实际上你是对的。问题是,一旦我阅读了所有的父文件夹,我需要集合来存储它的子文件夹,这就是为什么我决定使用hases。如果你有任何建议,请告诉我?是否可以使用数组重写?
ids = Folder.where(parent_id: 0, user_id: current_user).pluck(:id)
@subfolders = Folder.where(parent_id: ids).group_by(:parent_id)