【问题标题】:rails 5 scope has_many through distinct and whererails 5 范围 has_many 通过 distinct 和 where
【发布时间】:2018-03-20 19:13:33
【问题描述】:

是否可以在 rails 范围内同时使用 distinctwhere

# 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_manyscope 参数只是返回关系的东西,所以你可以说:

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

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

    如果你愿意的话。

    请记住,作用域可以访问specialtiesdoctor_specialties 表,因此name 可能会引用specialties.name。也许 Jeff 是一个需要多年特殊训练才能治疗他的高维护患者。

    另外,您可能希望像这样重写 where("name != 'Jeff'")

    where.not(specialties: { name: 'Jeff' })
    

    通过将 name 引用显式绑定到 specialties 来消除歧义,并使用拆分查询而不是 SQL sn-p。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-09
      • 2012-02-13
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 1970-01-01
      • 2023-03-10
      • 2016-08-23
      相关资源
      最近更新 更多