我正在寻找一种基于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])
答案 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)