views:

75

answers:

1

Hey guys, I'm making a site in Rails, and I want to add a vote up/down system like here in Stackoverflow.

Can anyone suggest how to do it? I do know that I'll enter each vote into the database, but I mean, how do I code the vote buttons? What will I use, can anyone help me. Ajax isn't required but it would be nice.

I was going to try to use a POST command and do something like this,

<form name="input" action="/grinders" method="POST">
<input type="hidden" name="id" value="<%=h grinder.id %>">
<input type="hidden" name="vote" value="up">
<input type="submit" value="Vote" />
</form>

But, I get an authenticity token error, and I honestly do not know how to work with the form helper.

+3  A: 

Have a votes table like so:

[PK] vote_id, vote_type (up/down), [FK] post_id, [FK] user_id, time [optional]

Also add a score field to your posts table

Then you could have the vote button access a link like: /vote/post_id/type/, eg: /vote/14098/up. This can be done with or without Ajax.

When the vote action is called, check if the user has previously voted on that post - if yes, deny it. If not, create a row with the relevant values in the votes table and update the score field in the posts table.

NullUserException
I was thinking something like that, but can't people hack something like that?
Rickmasta
What do you mean by "hack"? It doesn't matter if the user enters the URL directly. You should still verify whether or not a user is allowed to cast a vote before saving anything to the database.
NullUserException
Wrap that last paragraph in a transaction block and you're good to go.
Raphomet