0

These are my classes & relations

class User
  has_many :conversation_participants
  has_many :conversations, :through => :conversation_participants
end

class ConversationParticipant
  belongs_to :user
  belongs_to :conversation
end

class Conversation
  has_many :messages
  has_many :conversation_participants
  has_many :users, :through => :conversation_participants
end

So when I want to create a conversation between user_ids 12 and 15, I first want to check if a conversation between these two already exists. So what I need to find is this:

ConversationParticipants where user_id IN (12, 15) AND "both conversationparticipant rows have the same conversation id"

I lack the proper words to explain this query but I think everyone will get what I mean. "Does a conversation between these two users exist already?". I know neither how to do it in SQL nor Rails so any answer is appreciated.

EDIT The id of the conversation would not be known. I need to find if a conversation between those two user_ids exist.

Thanks -- Emil

Emil Ahlbäck
  • 6,085
  • 8
  • 39
  • 54

2 Answers2

1
class User
  has_many :conversations
  has_many :conversation_participants
  has_many :joined_conversations, :through => :conversation_participants, :source => :conversation
end

class ConversationParticipant
  belongs_to :user
  belongs_to :conversation
end

class Conversation
  belongs_to :user
  has_many :conversation_participants
  has_many :speakers, :through => :conversation_participants, :source => :user
end
VvDPzZ
  • 2,995
  • 1
  • 23
  • 28
  • belongs_to :user would imply that there's a user_id column in the conversations table, which there is not. I'll add the schema sometime tonight when I'm at my computer. – Emil Ahlbäck Apr 16 '12 at 13:13
0

You can try this

 @result = ConversationParticipants.where("user_id in ? AND conversation_id=?",[1,2,3,4],2)
Kashiftufail
  • 10,815
  • 11
  • 45
  • 79