Masudul
Masudul

Reputation: 21971

Count total association number on search result

I have following many-to-many association...

class User
   has_and_belongs_to_many :starred_jobs, class_name: "Job",
                           join_table: "starred_jobs"
end

class Job
     has_and_belongs_to_many :starred_by, join_table: "starred_jobs",
                              class_name: "User"
end

In a query, I get number of users between two dates like

users = User.where(created_at: start_date..end_date)

In a summary page, I want to view total number of jobs of selected users. Now, how I get the total number of jobs from searched users? For example:

@total_users_jobs = users.jobs.count 

Thanks in advance.

Upvotes: 1

Views: 153

Answers (2)

coderhs
coderhs

Reputation: 4847

Simplest and maybe resource heavy method would be

users.map { |u| u.jobs.count }.sum

another method

JobUser.where("user_id in (?)", users.map(&:id)).count

Another

Job.joins(:users).where(users: {id: users.map(&:id)}.uniq.count

Upvotes: 1

messanjah
messanjah

Reputation: 9288

This should give you the total count of all Jobs for all matching Users

@total_users_jobs = Job.joins(:users).where(users: {id: users.map(&:id)}.uniq.count

Upvotes: 1

Related Questions