Skip to content

Instantly share code, notes, and snippets.

@manishval
Last active December 20, 2015 07:28
Show Gist options
  • Save manishval/6093127 to your computer and use it in GitHub Desktop.
Save manishval/6093127 to your computer and use it in GitHub Desktop.
In your PhotoController index action get the top 3 un-voted photos:
```
@photos = Photo.unvoted.limit(3)
```
Then in your view you wrap each photo within a div, and give this div a data-id attribute with the photo's id as the value. Example:
```
<div id="photos">
<% @photos.each do |photo| %>
<%= render partial: 'vote_form', photo: photo %>
<% end %>
</div>
```
Create a partial so we're don't repeat code in index.html and update.js.erb.
```
# _vote_form.html.erb
<div class="photo" data-id="<%= photo.id %>">
# form code
</div>
```
```
/* CSS to show and hide */
#photos .photo {
display: none;
}
#photos .photo:first-child {
display: block;
}
```
The reason for this data-id attribute is for us to know which photo to remove after it has gotten a vote. Now, in your update.js.erb:
```
<% if @photo.errors? %>
# Handle voting errors
alert('<%= @photo.errors.full_messages.join(', ') %>');
<% else %>
# Remove photo
$('div[data-id="<%= @photo.id %>"]').remove();
# Display 2nd photo
$('#photos div:first-child').show();
# Add next photo
$('#photos').append('<%= escape_javascript(render partial: 'vote_form', photo: @next_photo) %>');
<% end %>
```
Make sure you grab next photo from the database.
```
# PhotosController
def update
@photo = Photo.find(params[:id]);
respond_to do |format|
if @photo.update_attributes(params[:photo])
# We're offsetting by 2 cause we already have the top 2 un-voted photos in the view
@next_photo = Photo.unvoted.limit(1).offset(2)
format.js
else
format.js
end
end
end
```
I haven't tried this code, so there might be a few hiccups. You can always shoot me a question if you need help.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment