Kellogs
Kellogs

Reputation: 471

Caching Issue with thumbs_up gem

The thumbs_up gem on github does not explain how to cache the votes in a different model.

This thumbs_up gem is connected to a user and a micropost and I want to create a column to the micropost table inorder to count the amount of votes the micropost has.

I am doing this so I can sort the microposts through the amounts of votes. All suggestions are very welcomed!

Also for those who are not familiar with this gem, here it is: https://github.com/brady8/thumbs_up

Upvotes: 3

Views: 226

Answers (1)

Don Leatham
Don Leatham

Reputation: 2704

I'm using the Thumbs_up gem on a project where a user writes reviews and other users vote on them. I ran into the same problem and came up with the solution below. It is not elegant but it works. I hope someone more experienced can provide a better solution.

In my user model I have:

class User < ActiveRecord::Base
  acts_as_voter
  has_karma(:chapters, :as => :user)  # tracks "up votes" for all a user's chapters 
  has_many :reviews
end

My reviews model has a :vote_cnt attribute and DB column that I update whenever a vote is cast:

class Review < ActiveRecord::Base
  attr_accessible :heading, :body, :notes, :published, :user_id, :vote_cnt
  acts_as_voteable
  belongs_to :user

  ###############################################################################
  #  update the vote_cnt field in the database, for sorting and query purposes.
  def update_vote_count
    if self.vote_count != self.vote_cnt
      self.vote_cnt = self.vote_count
      self.save
    end
  end
end

In my reviews controller I have an action to handle a click on the vote link in my review view:

  ################################################################
  def vote_for
    @review = Review.find(params[:id])
    begin # try-rescue
      current_user.vote_for(@review)
      @review.update_vote_count
      redirect_to review_path( @review ), :notice  => "Successfully voted for this review."
    rescue
      redirect_to review_path( @chapter ), :notice  => "Sorry, can't vote for a review twice, or you don't have voting rights."      
    end
  end

Now, after all that I can finally retrieve the set of reviews accessible by the current_user ordered by the reviews' vote count:

@reviews [email protected]_by(current_ability).order("vote_cnt DESC")

Like I said, not elegant, but it works. You can structure your microposts as I've structured my reviews and it should work for you. Hope this helps you out.

Upvotes: 1

Related Questions