I want to make a hash nest.

Asked 2 years ago, Updated 2 years ago, 43 views

class<<self
   def category_sort
     order(small_category_id: "asc", id: "asc")
     .group_by {|w|w.small_category.name}
   end
 end

The above results have the following hash:

small_category1=>[data1,data2,data3]
 small_category2=>[data4,data5]
 small_category3 = > [data6, data7, data8]

I have a big_category, so I want to hang small_categories related to each big_category, but I don't know how to write the program.

As a result, I would like to obtain the data with the following image.Small_category1 and small_category2 hang from big_category1 and small_category1 and small_category2 have images that seem to have relevant data.

big_category1=>small_category1=>[data1,data2,data3]
               =>small_category2=>[data4,data5]
 big_category2=>small_category3=>[data6,data7,data8]

I can do it by doing the following, but if there is a smarter way, please let me know.

class<<self
  def category_sort
    r=order(small_category_id: "asc", id: "asc")
        .group_by { | w | [w.small_category.big_category.name, w.small_category.name]}

    hash = Hash.new { | h,k | h[k] = {}}
    r.each do|k,v|
      hash[k[0]][k[1]]=v
    end
  end
end

ruby-on-rails ruby

2022-09-30 10:53

1 Answers

Once #group_by in the big_category, you can group the data in the big_category further in small_category by using #map.

def category_sort
  order(small_category_id: "asc", id: "asc")
    .group_by { | w | w.small_category.big_category.name}
    .map { | big_category, ws | [ big_category, ws.group_by { | w | w.small_category.name } }
    .to_h
end

Ruby 2.0 and earlier cannot use Array#to_h, so instead of to_h

.each_with_object({}){|(k,v),h|h[k]=v}

and so on.

If both small_category and big_category are ActiveRecord models, bulk loading related categories using #includes can reduce the number of queries.

def category_sort
  include(small_category::big_category)
    .order(small_category_id: "asc", id: "asc")
    ...
end

and so on. (It depends on how this method is used, so I can't say it should be done.)


2022-09-30 10:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.