Taylor
Taylor

Reputation: 177

Ruby code to count number of objects with a certain association

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!

Upvotes: 0

Views: 43

Answers (1)

engineersmnky
engineersmnky

Reputation: 29308

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.

Upvotes: 2

Related Questions