I have the following two methods which handle the liking and unliking of posts in my Rails application:
def create
@post = Post.find(params[:id])
if @post.present?
@like = Like.new(user_id: current_user.id, post_id: @post.id)
if @like.save
redirect_to post_redirect(@post), :notice => 'Liked!'
else
redirect_to post_redirect(@post), :alert => 'An error prevented you from liking this post!'
end
else
redirect_to post_redirect(@post), :alert => 'Invalid post!'
end
end
def destroy
@post = Post.find(params[:id])
if @post.present?
@like = Like.where(user_id: current_user.id, post_id: @post.id).first
if @like.destroy
redirect_to post_redirect(@post), :notice => 'Unliked!'
else
redirect_to post_redirect(@post), :alert => 'An error prevented you from unliking this post!'
end
else
redirect_to p, :alert => 'Invalid post!'
end
end
They both check that the post exists first and then creates or destroys the like record containing the post id and user id and redirects to the post with a message depending on the outcome.
In the Like model I prevent duplicate likes with: validates :user_id, uniqueness: {scope: :post_id}
However the methods feel quite bloated... is there a better way to handle this?