0

I have a Message model with user_id and sender_id attributes following model users message in rails 3 question

I try to query user conversations based on "sender_id"

I did this

  has_many :conversations, :class_name => 'Message', select: [:sender_id], group: [:sender_id]

But it only returns the message ID.

Message Load (0.8ms)  SELECT sender_id FROM "messages" WHERE "messages"."user_id" = 1 GROUP BY sender_id
=> [#<Message sender_id: 500>] 

The select was used because seems that Postgres requires to explicitly select the attributes to group but If I explicit add them I should be add them in the group clause as well which I don't want.

Any idea how to retrieve messages in a has_manyassociation grouped by the sender_id attribute?

Community
  • 1
  • 1
Martin
  • 11,216
  • 23
  • 83
  • 140

1 Answers1

1

You should be setting the foreign_key attribute to the column name sender_id:

has_many :conversations, :class_name => 'Message', :foreign_key => 'sender_id'

Edit: it seems like you're trying to OR two columns in your where statement, in which case associations are not appropriate.

Instead, put a method on your user that will return their conversations

class User < ActiveRecord::Base

  ...

  def conversations
    Message.where("user_id = ? OR sender_id = ?", id, id)
  end

  ...

end

Of course you can also set up sent and received messages associations for the user.

Sam Peacey
  • 5,964
  • 1
  • 25
  • 27
  • But in this case, the `sender_id` is not the `User`. I should be able to still retrieve messages with `Message.user_id` – Martin Feb 05 '13 at 09:23
  • Are you trying to set up an association that has both sent and received messages, so either the `sender_id` or the `user_id` equals the user id? If so grouping is the wrong concept, and I think you're better off creating the two associations for sent and received messages, then creating a scope for `conversations` – Sam Peacey Feb 05 '13 at 09:27
  • Could you provide an example of what you mean? – Martin Feb 05 '13 at 10:02
  • Ok, but back to my question, how are these conversations grouped by the person who sent it? I just want the latest message either sent or received for each user as a conversation. – Martin Feb 05 '13 at 15:18
  • I'm not sure exactly what you want - could you update your question with an example of the data you're expecting to be returned? I think grouping might be confusing things since in an active record / sql sense, that's to do with aggregating records. – Sam Peacey Feb 06 '13 at 00:35