Adding a “Like/Unlike” button to a post in Rails

前端 未结 4 2019
陌清茗
陌清茗 2021-02-04 22:34

The site is a simple community where each user creates posts and users may \"like\" them or \"unlike\" them.

I have a Post and a Like model. Currently, I\'m listing all

相关标签:
4条回答
  • 2021-02-04 22:48

    You should define association in user model

    if it's ror 2.* add method in User model. it should look like this:

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

    Assuming Like has fields user_id and post_id and of course in view

    if current_user.already_likes?(@post)
      #add unlike button
    end
    
    0 讨论(0)
  • 2021-02-04 22:48

    You want to search for a record that matches the user_id and post_id. If you find one, you want to show the 'unlike' button, b/c that means the user has 'liked' the post already. If you don't (it returns nil), you want to show the 'like' button.

    The following method returns nil if the user hasn't 'liked' the post, and not nil if the user has 'liked' the post.

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

    So you can say:

    if user_likes(1, 12).nil?
      # show like button
    else
      #show unlike button
    end
    
    0 讨论(0)
  • 2021-02-04 22:55

    Also you could add validation to your Like model like so:

    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
    
    0 讨论(0)
  • 2021-02-04 23:02

    create an action like this in your posts controller.

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

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

    0 讨论(0)
提交回复
热议问题