【Rails】Ajaxでいいね機能

$ rails g model likes user_id:integer blog_id:integer
class CreateLikes < ActiveRecord::Migration[5.2]
  def change
    create_table :likes do |t|
      t.references :user, foreign_key: true
      t.references :blog, foreign_key: true

      t.timestamps
    end
  end
end
rails db:migrate
class Like < ApplicationRecord
  belongs_to :user
  belongs_to :blog
end
class User < ApplicationRecord
  has_many :likes, dependent: :destroy
  has_many :like_blogs, through: :likes, source: :blog
end
class Blog < ApplicationRecord
  has_many :likes, dependent: :destroy
  has_many :like_users, through: :likes, source: :user
end
$ rails g controller Likes create destroy
resources :likes, only: [:create, :destroy]

(blogs_controller.rb)

def show
  @blog = Blog.find(params[:id])
  @like = current_user.likes.find_by(blog_id: @blog.id)
  @likes_count = Like.where(blog_id: @blog.id).count
end

(likes_controller.rb)

class LikesController < ApplicationController
  def create
    @like = current_user.likes.create(blog_id: params[:blog_id])
    @blog = @like.blog
    @likes_count = Like.where(blog_id: @blog.id).count
  end

  def destroy
    @like = Like.find(params[:id]).destroy
    @blog = @like.blog
    @likes_count = Like.where(blog_id: @blog.id).count
  end
end

(blogs/show.html.erb)

<div id="likes_area_<%= @blog.id %>">
  <%= render partial: 'likes/like', locals: { blog: @blog, like: @like }  %>
</div>

(likes/_like.html.erb)

<% if like.present? %>
  <%= link_to '解除', like_path(id: like.id), method: :delete, remote: true  %>
<% else %>
  <%= link_to 'いいね', likes_path(blog_id: blog.id), method: :post, remote: true  %>
<% end %>
<%= @likes_count %>

(likes/create.js.erb)

$('#likes_area_<%= @blog.id %>').html("<%= j(render partial: 'likes/like', locals: {blog: @blog, like: @like}) %>")

(likes/destroy.js.erb)

$('#likes_area_<%= @blog.id %>').html("<%= j(render partial: 'likes/like', locals: {blog: @blog, like: nil}) %>")