【问题标题】:Rails combinations of two columns两列的导轨组合
【发布时间】:2018-10-09 19:41:08
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: ruby-on-rails arrays activerecord


    【解决方案1】:

    我想你想要的是:

    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 将是您想要的哈希值。

    【讨论】:

      【解决方案2】:

      试试这个,messages 是你的消息。

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

      【讨论】:

        【解决方案3】:

        您仍然可以使用 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"}
          ]
         }
        

        【讨论】:

          猜你喜欢
          • 2016-09-15
          • 1970-01-01
          • 2017-04-03
          • 2018-06-25
          • 2015-02-22
          • 1970-01-01
          • 1970-01-01
          • 2016-05-14
          相关资源
          最近更新 更多