user3740962
user3740962

Reputation: 153

Rails find by has_many :through

I am looking for a way to query a model based on children in a has_many through 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 matches an array of ids.

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

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

Upvotes: 6

Views: 6143

Answers (3)

CoupDeMistral
CoupDeMistral

Reputation: 198

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

assuming that participant_id is the foreign key of participants in the conversation_participants table

Upvotes: 0

Mark Swardstrom
Mark Swardstrom

Reputation: 18100

Sounds like you just want the conversations, if so you can joins.

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

Otherwise, if you want to eager load the participants, use includes

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

Upvotes: 13

Arslan Ali
Arslan Ali

Reputation: 17812

You can pass an array like this:

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

Assuming that params[:participants] is an array.

Upvotes: 2

Related Questions