【问题标题】:rails 5 scope has_many through distinct and whererails 5 范围 has_many 通过 distinct 和 where
【发布时间】:2018-03-20 19:13:33
【问题描述】:
是否可以在 rails 范围内同时使用 distinct 和 where?
# this works
has_many: specialties, -> { distinct }, through: :doctor_specialties
# this also works
has_many: specialties, -> { where "name != 'Jeff'" }, through: :doctor_specialties
是否可以将它们组合成一个范围?
【问题讨论】:
标签:
ruby-on-rails
activerecord
rails-activerecord
【解决方案1】:
当然,has_many 的 scope 参数只是返回关系的东西,所以你可以说:
has_many :specialties, -> { distinct.where("name != 'Jeff'") }, ...
或
has_many :specialties, -> { where("name != 'Jeff'").distinct }, ...
如果你愿意的话。
请记住,作用域可以访问specialties 和doctor_specialties 表,因此name 可能会引用specialties.name。也许 Jeff 是一个需要多年特殊训练才能治疗他的高维护患者。
另外,您可能希望像这样重写 where("name != 'Jeff'"):
where.not(specialties: { name: 'Jeff' })
通过将 name 引用显式绑定到 specialties 来消除歧义,并使用拆分查询而不是 SQL sn-p。