Reputation: 8597
I'm able to like something and update the like count on the first click, but it doesn't work on the second click. I debugged it where the post needs to change, but I'm having trouble figuring out how to change the form method on the ajax call.
skit_controller.rb
def like
@skit.liked_by current_user if request.post?
@skit.unliked_by current_user if request.delete?
respond_to do |format|
format.html { redirect_to skits_path, notice: 'Successfully voted!' }
format.js
end
end
routes.rb
resources :skits do
resources :challenges
match :like, via: [:post, :delete], on: :member
end
index.html.haml
- @skits.each do |skit|
= render skit
_skit.html.haml
.votes
- method = current_user.liked?(skit) ? :delete : :post
= link_to like_skit_path(skit), method: method, remote: true, id: "post-#{skit.id}" do
.upvote
%span.upvote-link
%i.fa.fa-caret-up
.vote-count= skit.votes_for.size
like.js.erb
$("#post-<%= @skit.id %>").find(".vote-count").html('<%=j @skit.votes_for.size.to_s %>');
I think I need to update the method every time someone clicks the button, so user can :post
a like or :delete
a like, but it just stays at a POST method.
Upvotes: 0
Views: 25
Reputation: 1716
We will have to update a bit your layout.
.skit-wrapper{id: "skit-#{skit.id}"}
=render partial: 'skits/skit_wrapper', locals: {skit: skit}
.votes
- method = current_user.liked?(skit) ? :delete : :post
= link_to like_skit_path(skit), method: method, remote: true do
.upvote
%span.upvote-link
%i.fa.fa-caret-up
.vote-count= skit.votes_for.size
$("#skit-<%= @skit.id %>").html("<%= escape_javascript(render partial: 'skits/skit_wrapper', locals: {skit: @skit}) %>")
Upvotes: 1