是否可以在rails范围内同时使用distinct
和where
?
# this works
has_many: specialties, -> { distinct }, through: :doctor_specialties
# this also works
has_many: specialties, -> { where "name != 'Jeff'" }, through: :doctor_specialties
是否可以将它们组合成一个范围?
答案 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代码段。