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 to share