I have a Ruby on Rails project that includes a User
model and a Content
model, among others. I recently implemented a feature where users can "like" content using the acts_as_votable gem.
Currently, the liking functionality works as expected but it requires a page refresh every time a user clicks the like button.
I'm interested in incorporating Ajax into this feature to allow for updating the like button and counter without refreshing the entire page.
Here's a snippet from my Content -> Show
view:
<% 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 logic in the Content
controller for liking/disliking is as follows:
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, I've defined the following routes:
resources :contents do
member do
put "like", to: "contents#like"
put "dislike", to: "contents#dislike"
end
end
While the liking system is functional, it doesn't update the likes counter or the like button in real-time. To work around this, I currently use redirect_to @content
in the controller action.
Is there a way to implement this behavior with an Ajax call? Any suggestions on improving this process?