能否在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
相关产品推荐
相关产品推荐

