Joshua
Joshua

Reputation: 805

One Vote per IP address

I am trying to implement a voting system where votes are limited by the voters ip_address.

I have a post model which has many_votes and the votes belong_to the post model.

My question is how and where do I define the "current_user" and how can do i implement this in the view.

Currently I am creating votes like this:

<%= link_to(post_votes_path(post), :method => 'post') do %>
<%= song.votes.size %>

Works fine except anyone can vote and i want to stop that. Please i am not looking for a gem I am just trying to learn this functionality from scratch.

Cheers.

Here is my Posts controller code:

def create
@post = Post.new(params[:post])

respond_to do |format|
  if @post.save
    format.html { redirect_to root_url, notice: 'Post was successfully created.' }
  else
    format.html { render action: "new" }
  end
end
end

and vote controller code for create action:

def create
@post = Post.find(params[:post_id])
@vote = @post.votes.create
respond_to do |format|
  format.html { redirect_to root_url }
  #format.js 
end
end

Upvotes: 2

Views: 746

Answers (2)

Niels B.
Niels B.

Reputation: 6310

Like the MrYoshiji suggests, you should add a voter_ip column to your votes table.

You can add this AR where clause to your posts / votes controller

if @post.votes.where(voter_ip: request.remote_ip).empty?
  @post.votes.create(vote: params[:post_vote])
end

This will check of this post has any votes from the current ip. In case no votes are recorded, a new vote is added with the param value of post_vote

In case you prefer to add a constraint to your vote model, you need to do a scoped validation.

validates_uniqueness_of :voter_ip, scope: :post_id

When using the scope parameter the uniqueness constraint is applied to the combination of voter_ip and post_id, instead of voter_ip alone.

Upvotes: 1

Gene
Gene

Reputation: 46990

The votes table needs in ip column with a unique validation constraint. Then the controller's save will fail if you try to record more than one vote per ip, which you can detect and use to flash an error. You must post your controller code in order to get a better answer.

Upvotes: 1

Related Questions