Rails: Ajax update like and like count
I am able to update the like and unlike button via ajax, but I am not able
to update the like count.
Post has_many likes
Post has_many liking_users, :through => :likes, :source => :user
likes_controller.rb
def create
@like = Like.new(:post_id => params[:post_to_be_liked])
if @like.save
respond_to do |format|
format.html {redirect_to :back, notice: "Liked!"}
format.js
end
end
end
view.html.erb
<% @post = user.posts.first %>
<div id="send_like_for_<%= @post.id %>">
<% if @post.is_liked?(@post, current_user)%>
<%= render 'unlike'%>
<%else%>
<%= render 'like'%>
<%end%>
</div>
<div id="liked_<%= @post.id %>" %>
<%= render 'liked_users'%>
</div>
create.js.erb
$("#send_like_for_<%= params[:post_to_be_liked]%>").html("<%=
escape_javascript(render('users/unlike')) %>")
$("#liked_<%= params[:post_to_be_liked]%>").html("<%=
escape_javascript(render('users/liked_users')) %>")
_unlike.html.erb
<span> UNLIKE </span>
_liked_users.html.erb
<%= link_to "#{@post.likes.length} like this" %>
The like/unlike functionality works just fine and when someone likes the
post the button changes to Unlike. But the like count doesn't increase.
No comments:
Post a Comment