CertProgramItem has_many:cert_schedules。 CertSchedule belongs_to:reg_fee_item,:foreign_key => 'reg_fee_item_id',:class_name => '项'
从CertProgramItem开始,我想在一个查询中获取所有CertSchedules及其相关表(以避免n + 1问题)。我的第一个问题是:
cpi_arr = CertProgramItem.find(:all, :include => :cert_schedules, :order => :id)
但是,这并没有获取属于CertSchedules集合的Item类的成员。
我修改了查询:
cpi_arr = CertProgramItem.find(:all, :include => {:cert_schedules => :items}, :order => :id)
和
cpi_arr = CertProgramItem.find(:all, :include => {:cert_schedules => :reg_fee_items}, :order => :id)
但我收到类似ActiveRecord :: ConfigurationError的错误:找不到名为'items'的关联;也许你拼错了?“或者ActiveRecord :: ConfigurationError:没有找到名为'reg_fee_items'的协会;也许你拼错了它?第二个。
有没有办法在一个查询中获得这种嵌套的外键关联?
答案 0 :(得分:1)
以下是有关CertSchedule关联的更详细信息:
class CertSchedule < ActiveRecord::Base
belongs_to :cert_program_item
belongs_to :reg_fee_item, :foreign_key => 'reg_fee_item_id', :class_name => 'Item'
belongs_to :start_term, :class_name => 'SchoolTerm', :foreign_key => 'start_term_id'
我的查询的最新版本如下所示:
cpi_arr = CertProgramItem.find(:all, :include => [:cert_tier, {:cert_schedules => [:reg_fee_item,:start_term] }])
此查询现在成功返回我的预期。经验教训: