I have a model Painting
with many records. I'm printing them all, and for each one I want to attach some jQuery so that clicking on each Painting renders a partial with a large version of the Painting.
<div id="viewer"></div>
<% Painting.all.each_with_index do |painting, index| %>
<%= image_tag(painting.path, id:"painting"+index%>
<% @painting = painting %>
<script type="text/javascript">
$("#painting<%=index%>").click(function() {
$("#viewer").html("<%= escape_javascript(render 'partial') %>");
});
</script>
<%end%>
_partial.html.erb
<%= image_tag(@painting.path, class:"large-painting") %>
<!-- more code -->
The problem is, the value @painting
is reset with each loop, and by the end it's equal to the last Painting. So no matter which Painting I click on, the last one will always be the one rendered in the partial.
Can anyone think of a way to have the Painting rendered in the partial correspond to the one I click on, without writing separate jQuery for each one?
Can you add the URL for the large version of each image as a custom attribute on the image, then update the URL referenced by your Viewer with the URL corresponding with whatever image the user clicked on?
Something like:
$("#painting<%=index%>").click( function(){
$(Viewer_Image_Element).prop('src', $(this).prop('custom_URL_property'))
});
Alternatively, you could create a new controller action (or new response to an existing controller action) that responds by rendering the image partial. You could use $.ajax to call the controller action whenever someone clicks on an image, and send the image ID along as a param with the request. The server would use the param to properly render the partial and then send it back in its response. Then simply insert the html into the viewer. I can add some example code if this is the route you want to take.
This also means that the user doesn't need to download a large version of each image when they first load the page. This may or may not be a good thing.