user892050
user892050

Reputation: 21

Using :include with nested tables through foreign_key relationships

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

Starting with the CertProgramItem, I want to get all CertSchedules and their related tables in one query (to avoid the n+1 problem). My first query was:

cpi_arr = CertProgramItem.find(:all, :include => :cert_schedules, :order => :id)

However, this didn't fetch the members of the Item class which belong to the collection of CertSchedules.

I have modified the query:

cpi_arr = CertProgramItem.find(:all, :include => {:cert_schedules => :items}, :order => :id)

and

cpi_arr = CertProgramItem.find(:all, :include => {:cert_schedules => :reg_fee_items}, :order => :id)

but I get errors like ActiveRecord::ConfigurationError: Association named 'items' was not found; perhaps you misspelled it?" or ActiveRecord::ConfigurationError: Association named 'reg_fee_items' was not found; perhaps you misspelled it? for the 2nd.

Is there a way to get this nested, foreign-key association in one query?

Upvotes: 0

Views: 494

Answers (1)

Louise
Louise

Reputation: 11

Here's some more detailed information on the CertSchedule assocciations:

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'

My latest version of the query looks like this:

cpi_arr = CertProgramItem.find(:all, :include => [:cert_tier, {:cert_schedules => [:reg_fee_item,:start_term] }])

This query is now successfully returning what I expected. Lessons learned:

  • Use the foreign key name from the model, not the actual table name.
  • Multiple items in an association need to be surrounded with square brackets [].

Upvotes: 1

Related Questions