I have about 500 outlets. Each outlet will be monitored a minimum of one time per day. I am trying to get a list of outlets that have been monitored each day.
I am having a problem with the query at the moment, any help is appreciated:
<% for outlet in @outlets %>
<% if Monitoring.exists?( :outlet_id => outlet.id, 'DATE(created_at) = ?', Date.today ) %>
The @outlets is an instance variable containing Outlet.all.
This query leaves me with a syntax error. What would be the correct way to do this? I’m trying to check that the Monitoring belongs to the Outlet, and that the Monitoring record was created today.
Also, I’m not entirely sure of the speed implications of this query. There will be a max of 2000 outlets on a page at one time (it’s a dashboard, so they appear as either red or green dots).
Any help greatly appreciated.
You’re getting a syntax error because you’re trying to mix implicit-Hash and implicit-Array arguments:
The
exists?methods wants a Hash as its single argument. You want to use an SQL function in the query though, that means that you have to use theModel.where(...).exists?form:That still leaves you hitting the database over and over again to light up your lights. You could precompute the whole mess with something like this:
And then look use
counts.has_key? outlet.idin your loop. Adding awhere(:outlet_id => outlet_ids)(whereoutlet_idsare the IDs you’re interested in) might make sense as well. You might be able to combine thecountquery with the query that is generating the@outletstoo.