Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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])
like image 393
user3740962 Avatar asked Jun 25 '15 17:06

user3740962


1 Answers

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] } )
like image 171
Mark Swardstrom Avatar answered Sep 22 '22 01:09

Mark Swardstrom