通过has_many找到Rails:through

时间:2015-06-25 17:55:58

标签: ruby-on-rails ruby activerecord

我正在寻找一种基于has_many通过关联的子项查询模型的方法。

我有3个型号:

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

我需要找到参与者匹配一组ID的对话。

这就是我现在所拥有的(不工作):

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

3 个答案:

答案 0 :(得分:10)

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] } )

答案 1 :(得分:2)

您可以传递这样的数组:

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

假设params[:participants]是一个数组。

答案 2 :(得分:0)

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