Search code examples
ruby-on-railsrelationships

Rails, find by association


I'm about to build a messaging feature for a rails app.

I thought about having conversations, conversation_participants and conversation_messages.

Which means:

Conversation:

has_many :conversation_participants
has_many :conversation_messages, through: :conversation_participants

Conversation Participant:

belongs_to :conversation
belongs_to :user
has_many :conversation_messages

Conversation Message:

belongs_to :conversation_participant

So far, so good.

I'm just stuck in some scenarios:

  • How do I find the conversation for User 1 and User 2?
  • How do I find one for User 1, User 4 & User 5?
  • What if there are two conversations, one for Users 1,4,5 and one for 1,4,5,6 but I'm just looking for 1,4,5?

Hope somebody could help me out on this one! Thank you!


Solution

  • You can exclude converstion_messages. These are irrelevant, and need to include users.

    #user 
    has_many :conversations, through: converstion_participants
    
    user_12_conv_ids = user_1.conversation_ids & user_2.conversation_ids
    user_123_conv_ids = user_12_conv_ids & user_3.conversation_ids
    
    user_123_conversations = Conversation.where(id: user_123_conv_ids) 
    

    Now you can select conversations that include only 1, 2, and 3 (as user_ids)

    conversations.select{|c| c.user_ids == user_ids}