简体   繁体   English

Rails在每个do循环中形成嵌套哈希

[英]rails form nested hash in each do loop

Here is my method 这是我的方法

  def categories
    @categories = {}
    cat = Category.includes(:sub_categories).where('categories.status = ?', true).order(:id)        
    cat.each do |category|
        category.sub_categories.each do |sub_category|
            @categories[category.name] = { name: sub_category.name }
        end
    end
  end

What I am trying to do is 我想做的是

Assume my category.name is mobile phones and my sub_category.name will have list of mobile phone brands. 假设我的category.name是手机,而我的sub_category.name将具有手机品牌列表。 But my above method prints one sub category only because the name is variable but how to create nested hash. 但是我上面的方法只打印一个子类别,因为名称是可变的,但是如何创建嵌套的哈希。

Any other proper method of doing this 其他任何适当的方法

That's because you are overwriting the key in each subcategory. 那是因为您要覆盖每个子类别中的密钥。 You have to store an array of subcategories for each key: 您必须为每个键存储一个子类别数组:

{"name1"=>[{"subcategory1"=>...},{"subcategory2"=>...}],"name2"=>[]}

Try this: 尝试这个:

  def categories
    @categories = {}
    cat = Category.includes(:sub_categories).where('categories.status = ?', true).order(:id)        
    cat.each do |category|
        category.sub_categories.each do |sub_category|
            @categories[category.name] = [] unless @categories[category.name]
            @categories[category.name] << { name: sub_category.name }
        end
    end
  end

Also if the category.status is a boolean, you can do: 另外,如果category.status是布尔值,则可以执行以下操作:

cat = Category.includes(:sub_categories).where(status: true).order(:id)

And remove the sql query from a controller, which is ugly. 并从控制器中删除sql查询,这很丑陋。

EDITED 已编辑

As long as you have a hash of arrays, in order to render the view you will have to iterate again: 只要您具有数组的哈希值,为了呈现视图,您将不得不再次迭代:

@categories.each do |category, values|
  values.each do |sub_category|
    subcategory["what you need"]
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM