Rails - 可枚举组_按多个关联
我想按对象的许多关系对对象的集合进行分组...像这样
s.inventoryitems.group_by{|i| i.locations}
为了简单起见,这会返回这样的结果:
{[1, 2, 3]=>["a"], [2]=>["b", "c"], []=>["d"]}
我正在寻找这样的结果:
{[1] => ["a"], [2] => ["a","b","c"], [3] => ["a"], [] => ["d"]}
我正在努力重组事物,以便这可以所有这些都可以在更直观的数据库和数据库中完成。面向模型关联的方式,但与此同时,我需要立即实现它,并需要与一些 Ruby 进行争论,但我不确定。感谢您的帮助!
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!
如果你想像这样翻转结构,你需要扩展它,反转它,然后重新组合它。您可以简单地通过迭代并手动重新分组来完成此操作:
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: