Rails - 可枚举的Group_By多个关联 [英] Rails - Enumerable Group_By multiple associations
问题描述
我想通过它们有很多关系来分组对象的集合...像这样
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"]}
我正在重组事物,所以这些都可以在更多直观的DB&模型关联导向的方式,但同时我需要立即实现这一点,需要用一些Ruby来对其进行讨论,但我不确定。感谢您的帮助!
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!
推荐答案
您需要展开此操作,将其反转并重新对其进行分组,像那样的结构。你可以简单地通过遍历它并手动重新组合:
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"]}
这篇关于Rails - 可枚举的Group_By多个关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!