views:

69

answers:

2

Users can vote on posts, so I set a many to many relationship in rails:

users have many votes posts have many votes

posts have many users through votes users have many posts through votes

Is there a more elegant way to create a new vote than this:

user.votes.create(:post_id => post.id).save

? thanks

A: 

Vote does not deserve its own entity. Just add a counter (or two) to posts model. I'd suggest following code:

user.votes_for(post)

Or in case of stackexchange platform:

user1.votes_up(post)
user2.votes_down(post)
Eimantas
DISAGREE. How will you control for people voting multiple times for the same post? A separate model is much safer.
Ron Gejman
True, but you could make it more universal to have "activity" model that would log creation of comments, votes or any other user generated content.
Eimantas
You could, but then you would be folding vote validation logic into a "logging" class. That doesn't make too much sense either. Every time I've written a voting system I've used a separate model.
Ron Gejman
A: 

There is at least a "standard" way. I assume this is coming in from a form somewhere. So just pass in params like so:

 @vote = Vote.new(params[:vote])
 @vote.user = current_user
 if @vote.save
      ...
 else
      ...
 end
Ron Gejman