Rails - Enumerable Group_By multiple associations

假如想象 提交于 2019-12-10 11:16:16

问题


I want to group a collection of objects by their has many relations... like this

s.inventoryitems.group_by{|i| i.locations}

For the sake of simplicity this returns me something like this:

{[1, 2, 3]=>["a"], [2]=>["b", "c"], []=>["d"]}

I'm looking for a result like this though:

{[1] => ["a"], [2] => ["a","b","c"], [3] => ["a"], [] => ["d"]}

I am working on restructuring things so this can all be done in a more intuitive DB & model association oriented way, but in the meantime I need implement this immediately and need to wrangle it with some Ruby and am not sure. Thanks for any help!


回答1:


You need to expand this, invert it, and re-group it if you want to flip the structure like that. You could do this simply by iterating over it and regrouping manually:

h = { [ 1, 2, 3 ] => [ "a" ], [ 2 ] => [ "b", "c" ], [ ] => [ "d" ] }
s = { }

h.each do |keys, values|
  keys.each do |key|
    values.each do |value|
      s[[ key ]] ||= [ ]
      s[[ key ]] << value
    end
  end

  if (keys.empty?)
    s[[ ]] = values
  end
end

puts s.inspect
# => {[1]=>["a"], [2]=>["a", "b", "c"], [3]=>["a"], []=>["d"]}


来源:https://stackoverflow.com/questions/4684441/rails-enumerable-group-by-multiple-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!