I will put it together for myself.
** 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 becomes ** resource ** because it is not necessary to give an ID
post.rb
def liked_by?(user)
likes.where(user_id: user.id).exists?
end
You can check if you like it
likes_controller.rb
class LikesController < ApplicationController
def create
@post = Post.find_by(id: params[:post_id])
#Conditions to prevent 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
Since redirects are not required for create and destroy respectively, delete them if they are listed.
ruby:posts/show.html.slim
#Give an id because it is necessary to make it Ajax
div id='like_#{ @post.id }'
#Partial like icon
= 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 a 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! ** **
Recommended Posts