简体   繁体   中英

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. 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:

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

And remove the sql query from a controller, which is ugly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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