You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ruby on Rails控制器中关联User与Followed表查询用户

Rails 查询:筛选与followeds表followed_id匹配的用户

需求说明

需要在控制器中筛选出所有id与followeds表的followed_id字段匹配的用户记录,涉及模型为User和Followed,其中followeds表包含关联users表的user_id外键,以及整数类型的followed_id字段。

实现方案

方案一:子查询方式

直接通过子查询获取符合条件的用户ID集合,再匹配User表:

def index
  @users = User.where(id: Followed.pluck(:followed_id))
end

pluck(:followed_id)会提取followeds表中所有followed_id的值组成数组,where(id: 数组)会自动生成IN条件完成匹配。

方案二:关联查询方式(推荐)

先在User模型中定义关联关系,再通过关联查询获取结果:

  1. 在User模型中添加关联:
class User < ApplicationRecord
  # 关联followeds表中followed_id指向当前用户的记录
  has_many :follower_records, class_name: "Followed", foreign_key: "followed_id"
end
  1. 在控制器中使用joins关联查询,并用distinct去重:
def index
  @users = User.joins(:follower_records).distinct
end

这种方式符合Rails关联设计逻辑,查询效率更高,还能避免因关联多条记录导致的用户数据重复。

内容的提问来源于stack exchange,提问作者user20217103

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 12:21:49