[Ruby] Implementation of like function (Ajax)

less than 1 minute read

Collect for yourself.

Implementation

Controller model created

routes.erb


  Rails.application.routes.draw do
    resources :posts do
      resources :comments, only: [:create, :destroy]
      resource :likes, only: [:create, :destroy]
    end
  end

likes become resource because ID is not required

post.rb


  def liked_by? (user)
    likes.where(user_id: user.id).exists?
  end

You can check whether you like

likes_controller.rb


class LikesController <ApplicationController

  def create
    @post = Post.find_by(id: params[:post_id])
# Conditions for preventing continuous clicks
    unless @post.liked_by?(current_user)
      @like = current_user.likes.new(post_id: @post.id)
      @like.save
    end
  end

  def destroy
    @post = Post.find_by(id: params[:post_id])
    @like = current_user.likes.find_by(post_id: @post.id)
    @like.destroy
  end

end

Create and destroy redirects are no longer required, so delete them if mentioned.

ruby:posts/show.html.slim


Add id because it will be needed to make #Ajax
div id='like_#{ @post.id }'
   # Like icon partial
   = render'like', post: @post

ruby:posts/_like.html.slim


# Like Delete
- if post.liked_by?(current_user)
  = link_to post_likes_path(post), method: :delete, remote: true do
    i.fas.fa-heart style='color: red;'
    = post.likes.count

# How nice
- else
  = link_to post_likes_path(post), method: :post, remote: true do
    i.far.fa-heart
    = post.likes.count

Call the JavaScript file by adding remote: true

ruby:likes/create.js.erb


$("#like_<%= @post.id %>").html("<%= j(render'posts/like', post: @post) %>");

ruby:likes/destroy.js.erb


$("#like_<%= @post.id %>").html("<%= j(render'posts/like', post: @post) %>");

**Complete! **