Search code examples
ruby-on-railsrubyacts-as-votable

acts_as_votalble always shows link to dislike


I'm trying to use acts_as_votable in my Rails application. Currently I have a link to allow users to like or unlike a post. But right now it always shows the link to dislike ( the current_user has liked the status). This is even the case when I seed the database.

app/controllers/status_controller.rb

class StatusController < ApplicationController
  before_action :set_status

  def like
    current_user.liked_by @status
    respond_to do |format|
      format.js {render inline: "location.reload();" }
    end
  end

  def dislike
    current_user.unliked_by @status
    respond_to do |format|
      format.js {render inline: "location.reload();" }
    end
  end

  private

  def set_status
    @status = Status.find(params[:id])
  end

app/models/user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :confirmable, :lockable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :statuses, dependent: :destroy
  mount_uploader :images, ImageUploader
  mount_uploader :avatar, AvatarUploader
  acts_as_voter

  def age
    Time.now.year - birth_date.year
  end

  def name
    "#{first_name} #{last_name}".titleize
  end
end

app/models/status.rb

class Status < ActiveRecord::Base
  acts_as_votable
  belongs_to :user
end

app/views/welcome/home.html.slim

- @statuses.each do |status|
  .chip
    = cl_image_tag status.user.avatar.full_public_id, alt: status.user.name
    = " #{status.user.name} #{status.user.age}, #{status.user.city}, #{status.user.state}"
  p
    = status[:message]
  p
    - if current_user.voted_up_on? status
      = link_to dislike_status_path(status), method: :post, remote: true do
        i.small.material-icons.blue-text
          | thumb_up
    - else
      = link_to like_status_path(status), method: :post, remote: true  do
        i.small.material-icons.grey-text
          | thumb_up
    = time_ago(status.created_at)

Solution

  • It seems you like/unlike with a wrong way

      def like
        current_user.liked_by @status
    

    and

      def dislike
        current_user.unliked_by @status
    

    But you have to write @status.liked_by current_user and @status.unliked_by current_user

    Check documentation and examples:

    @post.liked_by @user1
    @post.unliked_by @user1