I’m trying to work out a more efficient way to add a note count, with a couple of simple where conditions applied to the query. This can take forever, though, as there are as many as 20K records to iterate over. Would welcome any thinking on this.
def reblog_array(notes)
data = []
notes.select('note_type, count(*) as count').where(:note_type => 'reblog', :created_at => Date.today.years_ago(1)..Date.today).group('DATE(created_at)').each do |n|
data << n.count
end
return data
end
This is what’s passed to reblog_array(notes) from my controller.
@tumblr = Tumblr.find(params[:id])
@notes = Note.where("tumblr_id = '#{@tumblr.id}'")
From what I can tell, you are trying to calculate how many reblogs/day this Tumblr account/blog had? If so,
should give you the right result, without having to iterate over the result list again. One thing to note, your call right now won’t indicate when there are days with 0 reblogs. If you drop the call to
#values, you’ll get a hash ofdate => count.As an aside and in case you didn’t know, I’d also suggest making more use of the ActiveRecord relations:
this way you avoid writing code like
Note.where("tumblr_id = '#{@tumblr.id}'"). It’s best to avoid string-interpolated parameters, in favour of code likeNote.where(:tumblr_id => @tumblr.id)orNote.where("tumblr_id = ?", @tumblr.id)to leave less chance that you’ll write code vulnerable to SQL injection