Implemented a like function so that other users can like the posting app. Suppose you have a users table, a posts table, and a likes table.
First, consider the relationship between each table and define the association. ** User (1): Likes (many) ** ** Post (1): Like (many) ** I want to make one ** like ** per person per post, so I will also validate it.
like.rb
class Like < ApplicationRecord
belongs_to :user
belongs_to :post
validates_uniqueness_of :post_id, scope: :user_id
end
If the post is deleted ** Like ** is also deleted.
post.rb
has_many :likes, dependent: :destroy
user.rb
has_many :likes, dependent: :destroy
def already_liked?(post)
self.likes.exists?(post_id: post.id)
end
likes_controller.rb
class LikesController < ApplicationController
def create
@like = current_user.likes.create(post_id: params[:post_id])
redirect_back(fallback_location: root_path)
end
def destroy
@post = Post.find(params[:post_id])
@like = current_user.likes.find_by(post_id: @post.id)
@like.destroy
redirect_back(fallback_location: root_path)
end
end
routes.rb
resources :posts do
resource :likes, only: [:create, :destroy]
end
post_likes
DELETE /posts/:post_id/likes(.:format) likes#destroy
POST /posts/:post_id/likes(.:format) likes#create
~.html.erb
<% if current_user.already_liked?(post) %>
<%= link_to post_likes_path(post), method: :delete do %>
<i class="fas fa-heart"></i>
<% end %>
<% else %>
<%= link_to post_likes_path(post), method: :post do %>
<i class="far fa-heart"></i>
<% end %>
<% end %>
<%= post.likes.count %> //Show the number of likes
Do you already like current_user?
If it is true, it will be unliked
, and if it is false, it will be liked
.
There are other ways to implement likes, such as asynchronous implementation. I'm still studying, but I would like to increase what I can study various techniques. Thank you for reading to the end: grin:
Recommended Posts