views:

29

answers:

1

I have created a blog application using Ruby on Rails which includes the ability to vote on posts. A user can click vote and a record is created in the vote table. I am now trying to limit that same person from voting for a post multiple times.

class Post
 has_many :votes
end


class Vote
 belongs_to :post
end

When a vote record is created I am using the VotesController to pass the :post_id and using a hidden field in the view to pass the ip_address (both to the vote table). I am wondering if there is a way to add a validation to the Vote Model that searches to see if a post_id has an ip_address that matches the person requesting to vote.

I have tried simply using the validates_uniqueness_of :ip_address but that restricts the user from voting on any post. I just want to restrict the user from voting on a particular post that they have already voted on.

Is there a way to do this through validation?

+5  A: 

try this:

class Vote
  belongs_to :post
  validates_uniqueness_of :ip_address, :scope => [:post_id]
end

This will validate uniqueness with regards to the post. User won't be able to vote twice for the same post.

In other news - you can get remote ip address from request.remote_ip. This is a wrapper for proxied ip addresses to so you won't have to worry about HTTP_X_FORWARDED_FOR and similar headers.

Eimantas
exactly same i am going to post but in gr8 style. 1 vote for excellent answer.
Salil
That did it. Thanks you very much. Perfect.
bgadoci