关联模型计数报错NoMethodError:雇主职位申请总数统计失败求助
Hey there! Let's break down why you're hitting that error and get it fixed quickly.
Why the error happens
When you call current_employer.jobs, you're getting a collection of Job records (Job::ActiveRecord_Associations_CollectionProxy), not a single Job instance. The job_applications method is defined on individual Job objects (thanks to the has_many :job_applications in your Job model), but collections don't have this method built-in. That's exactly why you're seeing undefined method 'job_applications' for #<Job::ActiveRecord_Associations_CollectionProxy:...>.
Fixes you can use
Option 1: Add a through association to Employer (cleanest Rails way)
The most idiomatic solution is to extend your Employer model to directly associate with job_applications through its jobs. This lets you call the count directly on the employer instance.
Update your employer.rb file:
class Employer < ApplicationRecord has_many :jobs, dependent: :destroy has_many :job_applications, through: :jobs # Add this line end
Now you can safely run:
<%= current_employer.job_applications.count %>
This works because Rails will automatically build the SQL query to count all job applications linked to any of the employer's jobs.
Option 2: Direct SQL query (no model changes needed)
If you don't want to modify the Employer model, you can query the job_applications table directly by joining with jobs:
<%= JobApplication.joins(:job).where(jobs: { employer_id: current_employer.id }).count %>
This is efficient because it runs a single SQL query to count the matching records, no extra model setup required.
Option 3: Sum counts across jobs (less efficient, for small datasets)
If you prefer to work with the existing associations (not recommended for large datasets), you can sum the counts of each job's applications. Just make sure to use includes to avoid N+1 database queries:
<%= current_employer.jobs.includes(:job_applications).sum { |job| job.job_applications.size } %>
Note: Use size instead of count here because includes preloads the job applications, so size uses the preloaded data instead of hitting the database again for each job.
Quick verification
After adding the through association (Option 1), fire up your Rails console and test it out:
current_employer = Employer.first # or fetch your current employer instance current_employer.job_applications.count # Should return the total number of applications across all jobs
内容的提问来源于stack exchange,提问作者Johnny C

