Skip to main content
1 of 3
Nivla
  • 53
  • 4

LikesControler for a Post - Rails

I have this controller that i call via ajax, where i update the likes of a post.

I have two methods in user model

already_like_post?: where i pass the post id and return true or false if he already like.

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

#This 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 dont know this looks good and its the rails way

Nivla
  • 53
  • 4