rails 5范围has_many通过distinct和where

时间:2018-03-20 19:13:34

标签: ruby-on-rails activerecord rails-activerecord

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

# this works
has_many: specialties, -> { distinct }, through: :doctor_specialties

# this also works
has_many: specialties, -> { where "name != 'Jeff'" }, through: :doctor_specialties

是否可以将它们组合成一个范围?

1 个答案:

答案 0 :(得分:3)

当然,scope的{​​{1}}参数只是返回一个关系,所以你可以说:

has_many

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

如果你愿意的话。

请注意,范围可以访问has_many :specialties, -> { where("name != 'Jeff'").distinct }, ... specialties表,以便doctor_specialties可能引用name。也许Jeff是一名​​高度维护的患者,需要多年的特殊训练才能治疗他。

另外,您可能想要像{i}这样重写specialties.name

where("name != 'Jeff'")

通过明确地将where.not(specialties: { name: 'Jeff' }) 引用绑定到name来消除specialties引用的歧义,并使用分解的查询而不是SQL代码段。