我一直在尝试以一种干净的方式基于3个关联之间的关联来聚合和计数记录。
好的,首先我有:
管理员用户
has_many :jobs
has_many :job_applications, through: :jobs
JobApplications
has_one :job_application_status_profile
job_application.rb
class JobApplication < ApplicationRecord
belongs_to :job
belongs_to :user
has_one :job_application_status_profile, dependent: :destroy
after_create :create_job_application_status_profile
end
job.rb
class Job < ApplicationRecord
belongs_to :admin_user
has_many :job_applications, dependent: :destroy
end
admin_user.rb
class AdminUser < ApplicationRecord
has_many :jobs, dependent: :destroy
has_many :job_applications, through: :jobs
end
我需要计算作业application_status配置文件通过作业is_review_complete有多少条记录->job_applications
current_admin_user.jobs.where(job_applications: {job_application_status_profile: {is_review_complete: false}}).size
简单地说,但我在做这件事时出错了。
我如何用最快的方法计算关系?
您需要使用eager_load
。试试这个
current_user.jobs.eager_load(job_applications:
[:job_application_status_profile]).where(job_applications:
{job_application_status_profile: {is_review_complete: false}}).size
参考文件:https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-eager_load
您缺少includes。试试这样的东西:
current_user.jobs.includes(job_applications:
[:job_application_status_profile]).where(job_applications:
{job_application_status_profiles: {is_review_complete: false}}).size
https://apidock.com/rails/ActiveRecord/QueryMethods/includes