0

Each of my app's Users can have multiple Passes. And each Pass can belong to a single Route. Passes can either be active or inactive.

I want to count the number of Users who have passes with an attribute of 'active' belonging to a specificed route.

What's the best way to go about doing this?

Thank you!

1 Answer 1

2

I hesitated to answer since I see no example of effort put in but...

I would do something like this because these seem useful separately as well.

class User
  ...
  has_many :routes, through: :passes
  scope :with_active_passes, ->{joins(:passes).where(passes:{active: true})}
  scope :by_route, ->(route){joins(:routes).where("routes.route_id = ?", route)}
end

Then you can call as

User.with_active_passes.by_route(route_id)

This will also allow you to use the separately as well like

User.with_active_passes #only users with active passes
User.by_route(route_id) # only users with passes that have a specific route_id
User.with_active_passes.by_route(route_id) # only users with active passes that have a specific route_id

Also you can change route_id to any column in route does not have to be id. To find out how many you can just add #size or #count to the end of the method chain.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. As I suspected, I was going about it in entirely the wrong way, chaining 'where' methods... so lack of evidence aside, my effort was misdirected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.