【问题标题】:Rails: Eager loading associated records with an outer joinRails:渴望加载具有外部连接的关联记录
【发布时间】:2015-09-03 03:30:01
【问题描述】:

我有一个表格,显示所有客户和每个客户的所有工作。为了加快页面加载速度,我必须预先加载相关的作业,如下所示。

但是,这种方法存在两个问题:

  1. 没有工作的Customers即使没有joins()方法也不会被加载

  2. 我必须使用慢速 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


【解决方案1】:

向客户添加 has_many

has_many :special_jobs, -> { where(booking_status: [2,3]).order(:id) }, :class_name => 'Job'

那就做吧

@customers = Customer.includes(:special_jobs).order(:id)

然后在视图中引用customer.special_jobs

# this is haml
- @customers.each do |customer|
  %tr
    %td= customer.name
    %td= customer.special_jobs.map { |job| link_to(job.name, job) }.join(', ')

【讨论】:

  • 像魅力一样工作。小拼写错误:Customer.includes 带有 s。
猜你喜欢
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 2013-02-17
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
相关资源
最近更新 更多