This might be a noob question. But I couldn’t figure it out by myself.
In my application’ I’m using Rails 3.2.8 with Mongoid and MongoDB.
I have a instance variable like this:
ProgramsController < ApplicationController
@program = Program.find(params[:id])
In my view file, I need to use it many many times. For example;
@program.title
@program.content
@program.schedules (associated with Schedule model)
@program.articles (associated with Article model)
etc.
The issue is, I need to use that instance variable at DIFFERENT parts of the view. So it’s not something like doing a @program.each do |t| ....
BUT when ever I use @program at a different part of the view, that means a NEW query each time…
At the moment I have 31 queries for my view. Isn’t it too much?
So what is the best practice? How should I use instance variables effectively?
Thanks in advance.
Once the item has been stored in
@program, it is indeed saved there and subsequent requests will not generate queries. If you only had references to@program.titleand@program.content, you would probably be fine. Your issue is from the associations, like@program.schedulesand@program.articles. The problem is that the schedules and articles are not being loaded from your@program = Program.find(params[:id]). This is referred to as the n+1 problem. The official docs state, under Eager Loading, thatEager loaded is supported on all relations with the exception of polymorphic belongs_to associations.andIn order for eager loading to work, the Identity Map must be enabled.. If these two conditions are true, you should see a reduction in your queries. If you cannot accomodate those requirements, a good solution might be to do somethign like this in the controller, to grab them all ahead of time, in one query:@schedules = Schedule.find_by(program_id: @program.id)