I have a Ruby on Rails project with a model User
and a model Content
, among others. I wanted to make possible for a user to "like" a content, and I've done that with the acts_as_votable gem.
At the moment, the liking system is working but I'm refreshing the page every time the like button (link_to) is pressed.
I'd like to do this using Ajax, in order to update the button and the likes counter without the need to refresh the page.
In my Content -> Show
view, this is what I have:
<% if user_signed_in? %>
<% if current_user.liked? @content %>
<%= link_to "Dislike", dislike_content_path(@content), class: 'vote', method: :put %>
<% else %>
<%= link_to "Like", like_content_path(@content), class: 'vote', method: :put %>
<% end %>
<span> · </span>
<% end %>
<%= @content.get_likes.size %> users like this
<br>
The Content
controller does this to like/dislike:
def like
@content = Content.find(params[:id])
@content.liked_by current_user
redirect_to @content
end
def dislike
@content = Content.find(params[:id])
@content.disliked_by current_user
redirect_to @content
end
And in my routes.rb file, this is what I have:
resources :contents do
member do
put "like", to: "contents#like"
put "dislike", to: "contents#dislike"
end
end
As I said, the liking system is working fine, but does not update the likes counter nor the like button after a user presses it. Instead, to trick that, I call redirect_to @content
in the controller action.
How could I implement this with a simple Ajax call? Is there another way to do it?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…