Martin
Martin

Reputation: 11336

has_many relationship with group

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?

Upvotes: 0

Views: 90

Answers (1)

Sam Peacey
Sam Peacey

Reputation: 6034

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.

Upvotes: 1

Related Questions