【问题标题】:Using :include with nested tables through foreign_key relationships通过foreign_key关系将:include与嵌套表一起使用
【发布时间】:2011-10-25 22:08:45
【问题描述】:

一个 CertProgramItem has_many :cert_schedules。 A CertSchedule belongs_to :reg_fee_item, :foreign_key => 'reg_fee_item_id', :class_name => 'Item'

从 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: Association named 'items' is not found 之类的错误;也许你拼错了?”或 ActiveRecord::ConfigurationError: Association named 'reg_fee_items' is not found;也许你拼错了?第二次。

有没有办法在一个查询中获得这种嵌套的外键关联?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案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] }])
    

    这个查询现在成功地返回了我所期望的。经验教训:

    • 使用模型中的外键名,而不是实际的表名。
    • 关联中的多个项目需要用方括号 [] 括起来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      相关资源
      最近更新 更多