1

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

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

That is working I used like this in view <% @categories.each do |category, sub_category| %> I can show <%= category %> but how to view the sub_category I tried sub_category.name but throwing error
Because you have two hashes, not objects. Adding solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.