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

Ruby Rails中如何获取where方法范围外的对象?

解决方案
  • 直接通过子查询一步获取
    无需提前查询持有目标帖子的用户集合,直接在数据库层面完成筛选:

    @users_without_goodbye_post = User.where.not(id: User.joins(:post).where(post: {content: "Goodbye!"}).select(:id))
    

    这种写法会生成高效的SQL语句,一次性完成排除操作。

  • 基于已有集合进行筛选
    如果你已经得到了@specified集合,可以提取其中的用户ID,再用where.not排除这些用户:

    @specified = User.joins(:post).where(post: {content: "Goodbye!"})
    @users_without_goodbye_post = User.where.not(id: @specified.pluck(:id))
    

为什么!@specified无效?

!是Ruby的布尔取反运算符,它会把@specified这个ActiveRecord集合对象转换为布尔值(集合非空则返回true,空则返回false),取反后得到的是false或true,并非你需要的用户集合,因此这种写法无法达到预期效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 16:42:01