Adding a Like / Unlike Button to a Post in Rails

The site is a simple community in which each user creates messages, and users can "like" them or "distinguish" them.

I have a Post and Like model. I am currently listing all posts, as well as the size of similar posts for each post via post.likes.size. A button to like the message also works.

What I don’t know how to do is how it depends on the case if the column should show a different button or something similar (depending on whether current_user likes this post).

A similar model is very simple:

User_id // current user
Post_id // post to associate

Thanks in advance!

+3
source share
4

2. * add . :

has_many :likes
def already_likes?(post)
  self.likes.find(:all, :conditions => ['post_id = ?', post.id]).size > 0
end

, user_id post_id , ,

if current_user.already_likes?(@post)
  #add unlike button
end
+5

, user_id post_id. , "unlike", b/c, , "". ( ), "".

nil, "" , , "" .

def user_likes(current_user, post_id)
  likes.find(:first, :conditions => ['user_id = ? AND post_id = ?', current_user, post_id] ).nil?
end

, :

if user_likes(1, 12).nil?
  # show like button
else
  #show unlike button
end
+1

Like :

validate :user_does_not_already_like_post

def user_does_not_already_like_post
  errors.add(:user, "You can only like a post once.") if user.already_likes?(post)
end
+1

.

def unlike
   # get the post
   #code to decrement the like counter of a specific post
end

then from your view, create a button or link pointing to this action.

0
source

Source: https://habr.com/ru/post/1769021/


All Articles