I have this controller that I call via Ajax, where I update the likes of a post.
I have two methods in the user model:
already_like_post?
: Where I pass the posted ID and return true or false if the post is already liked.dislike_post
: Delete the user like for given post.
class LikesController < ApplicationController
def create
if !current_user.already_liked_post? params[:post_id]
like = Like. new user: current_user, post_id: params[:post_id]
if !like.save
render json: like.errors
end
else
current_user.dislike_post params[:post_id]
end
amount_of_likes = Post.find(params[:post_id]).likes.count
render json:{status:"success",likes: amount_of_likes}
end
end
These are the methods in the user model:
def already_liked_post?(post_id)
self.likes.where(post_id: post_id).size == 1
end
def dislike_post(post_id)
self.likes.find_by(post_id: post_id).destroy
end
Can you give a review of this? I don't know if this looks good or if it is the Rails way.