You can use includes
method for eager loading the data. Also, using include for this situation will create a join query that will fetch only those programs which are related to both location and client.
@client.locations.includes(:programs).each do |location|
<h2>location.name</h2>
<ul>
location.programs.each do |program|
<li>program.name</li>
end
</ul>
end
Though you should avoid using database queries in view files. So you can move @locations = @client.locations.includes(:programs)
to your controller action and use @locations
in view to maintain the structure.