gpt4 book ai didi

ruby-on-rails - 通过 has_many 找到 Rails :through

转载 作者:数据小太阳 更新时间:2023-10-29 07:10:39 26 4
gpt4 key购买 nike

我正在寻找一种方法来通过关联查询基于 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])

最佳答案

听起来你只是想要对话,如果是这样你可以加入

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

否则,如果您想预先加载参与者,请使用includes

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

关于ruby-on-rails - 通过 has_many 找到 Rails :through,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31057408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com