ActiveRecord Group由2列组成

时间:2015-05-23 15:46:03

标签: ruby-on-rails ruby-on-rails-3 activerecord

Message型号

user_id      # owner of the message 
sender_id    # user that sent message
receiver_id  # user then recieved message 
content      # content of message

我有Messages。我想按sender_idreceiver_id对它们进行分组,因为这些是#34;会话主题"。

当我进行分组时,我得到的结果看起来像

[1,3] => 5   # user 1 and 3 have 5 messages
[1,6] => 2   # user 1 and 6 have 2 messages
[3,1] => 3   # user 3 and 1 have 3 messages

真的[1,3]和[3,1]属于同一组'。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

您可以使用sender_idrecipient_idLEAST()GREATEST()进行排序(至少在Postgres和MySQL中)。

这是展示SQL的fiddle

SELECT 
  LEAST(sender_id, receiver_id),
  GREATEST(sender_id, receiver_id),
  count(*)
FROM messages
GROUP BY
  LEAST(sender_id, receiver_id),
  GREATEST(sender_id, receiver_id)

ActiveRecord等价物:

Message.group('LEAST(sender_id, receiver_id), GREATEST(sender_id, receiver_id)').count

答案 1 :(得分:2)

使用@Kristján提供的技巧,您可以在ruby中合并[1,3][1,3],而不是使用SQL函数:

thread_messages_count = Hash.new(0)
Message.group(:sender_id, :receiver_id).count.each do |k, v|
  thread_messages_count[k.sort] += v
end