简体   繁体   中英

validating creation by post_id and ip_address - Ruby on Rails

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM