A very simple version might look like this:
Ruby
def vote @post = Post.find(params[:post_id]) @post.liked_by current_user respond_to do |format| format.html {redirect_to :back } format.json { render json: { count: @post.liked_count } } end end
HTML
<%= link_to 'like', vote_path(@post), class: 'vote', remote: true, data: { type: :json } %>
Js
$('.vote') .on('ajax:send', function () { $(this).addClass('loading'); }) .on('ajax:complete', function () { $(this).removeClass('loading'); }) .on('ajax:error', function () { $(this).after('<div class="error">There was an issue.</div>'); }) .on('ajax:success', function (data) { $(this).html(data.count); });
This is a very rudimentary version that shows a basic approach, but has some obvious pitfalls:
- Unable to "display"
- The download indicator is small UX; with JS, we can always display the current state of the user and deal with synchronization with the server in the background.
- Any caching of HTML in the view will blow it.
Wheeyls
source share