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

Rails查询users表indication_code与my_code_invite_win值相同的用户

Rails实现同记录两字段值相等的用户查询

直接在数据库层做字段比对查询即可,性能远高于Ruby内存遍历筛选,适合所有数据量级场景:

  • 通用基础写法(兼容MySQL、PostgreSQL、SQLite,默认排除两个字段同时为NULL的记录,SQL中NULL=NULL的判定结果为不相等)
# 返回所有indication_code与my_code_invite_win值相等的用户记录
@matching_users = User.where("indication_code = my_code_invite_win")
  • 特殊场景:如果业务上需要将两个字段同时为NULL的记录也纳入匹配结果,可根据当前使用的数据库选择对应语法:
    • MySQL环境使用安全等于运算符:
    @matching_users = User.where("indication_code <=> my_code_invite_win")
    
    • PostgreSQL、SQLite环境使用IS NOT DISTINCT FROM语法:
    @matching_users = User.where("indication_code IS NOT DISTINCT FROM my_code_invite_win")
    
  • 复用性优化:如果这个查询逻辑需要在多处调用,可以封装为模型作用域
    1. 打开app/models/user.rb文件,添加scope定义:
    class User < ApplicationRecord
      # 筛选邀请码与标识码一致的用户
      scope :with_matched_code, -> { where("indication_code = my_code_invite_win") }
    end
    
    1. 在控制器、业务服务中直接调用即可:
    @matching_users = User.with_matched_code
    

避坑提示:不要使用User.all.select { |user| user.indication_code == user.my_code_invite_win }这类全表加载后内存筛选的写法,当表数据量达到千级以上时会出现明显的响应延迟,数据量过万时甚至会直接撑爆应用内存。

内容的提问来源于stack exchange,提问作者Roberto da Silva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 16:01:04