【发布时间】:2015-09-03 03:30:01
【问题描述】:
我有一个表格,显示所有客户和每个客户的所有工作。为了加快页面加载速度,我必须预先加载相关的作业,如下所示。
但是,这种方法存在两个问题:
没有工作的
Customers即使没有joins()方法也不会被加载我必须使用慢速 Ruby 为每个客户按
jobs.id排序作业。
有解决办法吗?
# http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-eager-loaded-associations
@customers = Customer.all.includes(:jobs).where(jobs: {booking_status: [2,3]}).order('users.id ASC').references(:jobs)
@customers.each do |customer|
puts customer.full_name
jobs = customer.jobs.sort_by {|job| job.id}
jobs.each do |job|
puts job.id
【问题讨论】:
-
由于您的 where 子句,您没有获得非工作客户。您是说您只需要具有特定 booking_status 的客户。尝试将 where 子句替换为:
where("jobs.booking_status = ? OR count(jobs) = ?", [2,3], 0)
标签: ruby-on-rails ruby activerecord