user2954587
user2954587

Reputation: 4861

rails 5 scope has_many through distinct and where

Is it possible to use both distinct and where in a rails scope?

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

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

Is it possible to combine them into one scope?

Upvotes: 3

Views: 1057

Answers (1)

mu is too short
mu is too short

Reputation: 434665

Sure, the scope argument to has_many is just something that returns a relation so you could say:

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

or

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

if you wish.

Keep in mind that scope will have access to the specialties and doctor_specialties tables so that name would probably be referencing specialties.name. Perhaps Jeff is a high maintenance patient that requires years of special training to treat him.

Also, you might want to rewrite that where("name != 'Jeff'") like this:

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

to disambiguate the name reference by explicitly tying it to specialties and use a broken out query rather than an SQL snippet.

Upvotes: 3

Related Questions