pinkfloyd90
pinkfloyd90

Reputation: 678

Applying a scope from a related model to a query

I have two models, User and Payment. A User has_many Payments and a Payment belongs_to a User.

I'm querying all Payments for the current month like so:

@payments = Payment.approved.current_month

But I need to exclude Payments made by superadmin Users, for which I have the scope :exclude_superadmins in my User model which will exclude from a User query all users that are superadmins (determined by the User.permission_level).

I can't find a way to chain the :exclude_superadmins User scope to the Payment query, as it results in

NoMethodError: undefined method `exclude_superadmins' for #<Payment

I've tried including, joining and merging the table Users in the query with no success either.

Upvotes: 1

Views: 23

Answers (1)

razvans
razvans

Reputation: 3251

Take a look at merge. Below is an example on how it would be used in your scenario.

@payments = Payment.joins(:users).approved.merge(User.exclude_superadmins)

Upvotes: 1

Related Questions