Rails find by has_many: via

I'm looking for a way to query a model based on children in a has_many association.

I have 3 models:

class Conversation < ActiveRecord::Base
   has_many :conversations_participants
   has_many :participants, through: :conversations_participants
end

class ConversationsParticipant < ActiveRecord::Base
   belongs_to :conversation
   belongs_to :participant, class_name: 'User'
end

class User < ActiveRecord::Base
   has_many :conversations_participants
   has_many :conversations, through: :conversations_participants
end

      

I need to find conversations where participants match an array of IDs.

This is what I have at the moment (not working):

Conversation.includes(:participants).where(participants: params[:participants])

      

+3


source to share


3 answers


Sounds like you just need some conversations if you can joins

.

Conversation.joins(:participants).where(:users => { :id => params[:participants] } )

      



Otherwise, if you want to upload members, use includes

Conversation.includes(:participants).where(:users => { :id => params[:participants] } )

      

+8


source


You can pass an array like this:

Conversation.includes(:participants).where(:id => params[:participants])

      



Assuming it params[:participants]

is an array.

+2


source


Conversation.includes(:participants).where( 'conversation_participants.participant_id' => params[:participants])

      

assuming participant_id is a foreign key of the participants in table convers_participants

0


source







All Articles