Efficient Querying and Preloading Related to Images

Hi,
I’m working on a photo queue (think of a carousel that displays a single image at a time) that allows the user to upvote/downvote/skip each image. To reduce lag time, I want the next 2-3 photos that will be shown next to be preloaded in the background and ready to go. I haven’t quite figured out the best way to to accomplish this. My current setup is to get the first image in the queue in the Index action of the controller.

class PhotosController < ApplicationController
    def index
      @photo = Photo.unvoted.first
    end
end

Then when the user votes on the image, the update.js.erb is rendered and is redirected to the Index action where the next image that has not been voted on is shown.

The voting form looks like this:

    <%- 3.times do |n| %>
        <%= form_for @photo, remote: true do |f| %>
          <%= f.hidden_field :photo_rating, value: n %>
          <%= f.submit n, class: "btn" %>
        <% end %>
    <% end %> 

My main two questions are:

(1) How can I minimize the number of queries? This probably involves modifying the controller action.
(2) What’s a good way to handle preloading images the Rails way?

Even if you have advice or suggestions related to other issues, I’d love to hear them. Thanks!

Hey realDLee,

I don’t think you need to worry about minimizing the number of queries at this point. You’re only handling one query right now.

As for preloading images in Rails. You can use a jQuery library that will preload the images for you (GitHub - farinspace/jquery.imgpreload: The jQuery.imgpreload plugin lets you preload images before and after the DOM has loaded.) before the page loads.

In terms of your solution, might I suggest this approach. Instead of pulling one image from the database, pull the top 3 un-voted photos, display the first one and hide the 2nd and 3rd photo in the DOM. And then in the update.js.erb, remove the first image, unhide the 2nd image and add the next un-voted photo to the page.

I couldn’t post my code cause discourse thinks I’m mentioning users when I enter a ruby instance variable. And since I’m new I can not mention more that 2 users. Am I doing something wrong? Is there a way around this?

However I made a gist: gist:6093127 · GitHub