Rails - 可枚举组_按多个关联

发布于 10-12 05:37 字数 434 浏览 7 评论 0原文

我想按对象的许多关系对对象的集合进行分组...像这样

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤独岁月2024-10-19 05:37:43

如果你想像这样翻转结构,你需要扩展它,反转它,然后重新组合它。您可以简单地通过迭代并手动重新分组来完成此操作:

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"]}

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"]}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文