两列的Rails组合

时间:2018-10-09 19:41:09

标签: ruby-on-rails arrays activerecord

在我的Ruby on Rails项目中,我有一个Message模型,该模型具有directionfromto列。 direction可能是“传入”或“传出”。

我想通过其fromto字段将消息分组为对话。假设我的数据库中有以下消息:

{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']]的哈希。即使它们的顺序不同,在这里我也重复按键。

谢谢!

3 个答案:

答案 0 :(得分:0)

我认为您想要的是:

direction = Hash.new

Message.all.each do |message|
  if message.direction == "incoming"
    from = message.from
    to = message.to
  else
    from = message.to
    to = message.from
  end

  direction[[from, to]] ||= []
  direction[[from, to]] << "message with id #{message.id}"
end

现在direction将成为您想要的哈希。

答案 1 :(得分:0)

尝试一下,其中messages是您的消息。

messages.group_by do |m|
  m.direction == "incoming" ? [m.from, m.to] : [m.to, m.from]
end

答案 2 :(得分:0)

您仍然可以使用group_by进行此操作-您只需要具体说明用于分组的密钥即可。由于您不在乎消息的方向性,无论消息是传入还是传出,您都可以简单地对from和to的排序列表进行分组。因此,10000-> 2222.和2222-> 10000都在[10000,2222]的哈希键下分组,并且您的邮件按照您期望的方式分组。

messages = [
  {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'}
]

messages = messages.group_by do |x|
  [x[:from], x[:to]].sort
end

这将返回:

{
  ["10000", "2222"]=>[
    {:id=>1, :direction=>"incoming", :from=>"10000", :to=>"2222"},
    {:id=>2, :direction=>"outgoing", :from=>"2222", :to=>"10000"}
  ],
  ["10001", "3333"]=>[
    {:id=>3, :direction=>"incoming", :from=>"10001", :to=>"3333"},
    {:id=>4, :direction=>"outgoing", :from=>"3333", :to=>"10001"}
  ]
 }