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

能否在Rails 5的scope中同时使用distinct和where?

当然可以!两种Scope逻辑能合并到同一个关联中

完全没问题呀!你可以把distinct去重和where筛选这两个查询逻辑,直接通过链式调用放到同一个lambda块里,Rails的Active Record查询接口完全支持这种组合写法。

直接可用的合并写法

has_many :specialties, -> { distinct.where("name != 'Jeff'") }, through: :doctor_specialties

如果想要更好的可读性,也可以拆成多行书写:

has_many :specialties, 
         -> { 
           distinct
           .where("name != 'Jeff'")
         }, 
         through: :doctor_specialties

原理说明

lambda里的每个查询方法(比如distinct、where)都会返回一个Active Record关系对象,所以我们可以一直链式调用下去,把多个查询条件组合在一起,它们之间不会互相冲突,能正常生效。

额外小建议

如果你的Rails版本支持,推荐用参数化的查询写法来替代直接写SQL字符串,这样能避免SQL注入风险,代码也更优雅:

has_many :specialties, -> { distinct.where.not(name: 'Jeff') }, through: :doctor_specialties

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:08:19