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

前端 未结 4 2023
陌清茗
陌清茗 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 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
    

提交回复
热议问题