Rails: Eager loading for models three associations away -


i want show table of schedules , associated classes, partners, , locations in table columns.

# view <% @schedules.each |schedule| %>   <%= schedule.date.strftime("%d %b %y") %>   <%= schedule.klass.name %>   <%= schedule.partner.company %>   <%= schedule.partner.city.name %>   <%= schedule.start_time.strftime("%l:%m%p") %> -   <%= schedule.end_time.strftime("%l:%m%p") %> <% end %>  # models schedule    belongs_to :klass   belongs_to :partner klass   belongs_to :partner partner   belongs_to :city   has_many   :klasses   has_many   :schedules city   none  # controller schedules @schedules = schedule.includes(:klass, :partner).order(:date, :start_time, :end_time) 

unfortunately when page loads runs city queries multiple times.

select "schedules".* "schedules"  order "schedules"."date" asc, "schedules"."start_time" asc, "schedules"."end_time" asc select "klasses".* "klasses" "klasses"."id" in (6, 1, 7, 9, 10, 3) select "partners".* "partners" "partners"."id" in (3, 4, 2) select "cities".* "cities" "cities"."id" = $1 limit 1  [["id", 23]] select "cities".* "cities" "cities"."id" = $1 limit 1  [["id", 24]] 

i tried this:

schedule.includes(:klass, :partner).includes(:city) 

but gives me error:

association named 'city' not found on schedule; perhaps misspelled it? 

i've read rails guide on active record query have no idea on how improve query. appreciated. thanks.

schedule    belongs_to :klass   belongs_to :partner klass   has_many   :schedules   has_many :partners, through: :schedules partner   belongs_to :city   has_many   :schedules   has_many   :klasses, through: :schedules  city   has_many :partners 

the query should be

@schedules = schedule.includes(:partner => :city).order(:date, :start_time, :end_time).select('partners.*, cities.name') 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -