【发布时间】:2018-10-09 19:41:08
【问题描述】:
在我的 Ruby on Rails 项目中,我有一个 Message 模型,它具有 direction、from、to 列。 direction 可以是“传入”或“传出”。
我想通过 from 和 to 字段将消息分组到对话中。假设我的数据库中有以下消息:
{id: 1, direction: 'incoming', from: '10000', to: '2222'}
{id: 2, direction: 'outgoing', from: '2222', to: '10000'}
{id: 3, direction: 'incoming', from: '10001', to: '3333'}
{id: 4, direction: 'outgoing', from: '3333', to: '10001'}
最后我想要一个看起来像{['10000','2222']=>[message with id 1, message with id 2], ['10001','3333']=>[message with id 3, message with id 4]}的哈希
我已经尝试过 Message.all.group_by{|m| [m.from, m.to]} 但这会给我一个带有键 [['10000', '2222'], ['2222','10000'],['10001', '3333'], ['3333','10001']] 的哈希值。在这里,我有重复的键,即使它们的顺序不同。
谢谢!
【问题讨论】:
标签: ruby-on-rails arrays activerecord