Voting System


Once again, its been a while! We’ve recently bought a new house and moved so that’s pretty much consumed any free time I’ve had…Still is really.

I’ve been busy at work getting our newly acquired rails 2 app up to rails 4. Overall, it’s gone fairly well..There were some big changes although they have gone smother than I anticipated. Not to bore you with that, I wanted to write briefly about a voting system I was building for a personal project I’ve been working on.

So, voting. I basically wanted a reddit like up/down vote with a count. This would be for recipes (beer). I also didn’t want to use a gem, not because there aren’t good onces out there, but I wanted to give it a shot myself and see how far I could get without other resources (i.e blog posts/ tutorials).

Here was my first shot! Unfortunately, it lacked one fundamental feature..

I started with a migration adding a column to my beers table that would handle the vote_count.

class AddVoteCountToBeers < ActiveRecord::Migration
  def change
    add_column :beers, :vote_count, :integer, :null => false, :default => 0
  end
end

Added a couple of routes.

  get 'upvote/:id', to: 'beers#upvote', as: 'upvote'
  get 'downvote/:id', to: 'beers#downvote', as: 'downvote'

Couple of new methods in the Beer model.

  def upvote
    increment!(:vote_count)
  end

  def downvote
    decrement!(:vote_count)
  end

And finally, the controller.

  def upvote
    beer = Beer.find(params[:id])
    beer.upvote
    redirect_to :back
  end

  def downvote
    beer = Beer.find(params[:id])
    beer.downvote
    redirect_to :back
  end

Now, in the view I added a few up / down glyphicons and sure enough, voting! Although, I quickly realized a problem. There was no relationship between the user and their votes, I could sit there and keep clicking continuing to up/down vote…No Buena.

I’ve now set out to remedy this, which I figured involved a new votes table which references users along with beers. The method behind this will be a little different which I am working out now. So, Im going to fix this and see what I come up with. Standby!

comments powered by Disqus