use*_*962 5 ruby activerecord ruby-on-rails
我正在寻找一种方法来查询基于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
Run Code Online (Sandbox Code Playgroud)
我需要找到参与者匹配一组id的对话.
这就是我现在所拥有的(不工作):
Conversation.includes(:participants).where(participants: params[:participants])
Run Code Online (Sandbox Code Playgroud)
Mar*_*rom 11
听起来你只想要对话,如果可以的话joins.
Conversation.joins(:participants).where(:users => { :id => params[:participants] } )
Run Code Online (Sandbox Code Playgroud)
否则,如果您想加载参与者,请使用 includes
Conversation.includes(:participants).where(:users => { :id => params[:participants] } )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4031 次 |
| 最近记录: |