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

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

提交回复
热议问题