Background:
I’m creating a dashboard as a project and I have a query that I think is going to be a big performance issue:
<% for outlet in @outlets %>
<% if Monitoring.where(:outlet_id => outlet.id).where('date(created_at) = ?', Date.today).exists? %>
<li>
<a class="done" href="<%= outlet_url(outlet) %>" rel="tooltip" title="<%= outlet.name %>"></a>
</li>
<% else %>
<li>
<a href="<%= outlet_url(outlet) %>" rel="tooltip" title="<%= outlet.name %>"></a>
</li>
<% end %>
<% end %>
What I’m trying to achieve is a series of dots on a page. If the anchor tag has a class of done, it will display as green, if not it will be red (done through CSS).
Aside from the obvious DRY issues here, this query is very heavy, so I’m looking at ways to improve it.
An Outlet is Monitored at least once a day (An Outlet has_many :monitorings). For each outlet I need to check if it has been monitored on that particular day, and output the HTML accordingly.
If anyone could help me with this it would be fantastic.
(Also, any advice on caching this would be appreciated).
Cheers in advance :).
You might make a conditioned association for current monitors, then use includes to fetch the associated current monitorings on the original query.
At the Postgres level, you’ll likely benefit from an index on monitorings(outlet_id,created_at) to support the outer join implied by #includes.
BTW, it’s bad style to be executing database queries in your view. Put the domain logic in your models, and have your controller execute the query and supply the results to the presentation layer.