acts_as_votable using ip address

244 views Asked by At

I want to allow users to vote on posts without signing up, and have the vote instead tied to their ip address. I tried following this post but I need some more clarification. this is the error im getting from the posts_controller

undefined method `find_or_create_by_ip' for #

This is my code so far:

posts_controller:

def upvote 
    @post = Post.find (params[:id])
    session[:voting_id] = request.remote_ip
    upvote = session.find_or_create_by_ip(session[:voting_id])
    @post.upvote
    redirect_to :back
  end

  def downvote  
    @post = Post.find (params[:id])
    session[:voting_id] = request.remote_ip
    downvote = session.find_or_create_by_ip(session[:voting_id])
    @post.downvote
    redirect_to :back
  end 

session model:

 class session < ActiveRecord::Base
    acts_as_voter
    request.remote_ip
end

routes.rb:

Rails.application.routes.draw do
  get 'static_pages/home'
  get 'static_pages/about'
  resources :posts do
    member do 
      put "like" , to: "posts#upvote"
      put "dislike" , to: "posts#downvote"
    end
  end

In the other post someone said add an ip column to the sessions table. What exactly does that mean? I also saw somewhere that I would need to create a db table as well. do I? and how would I do that? Sorry about having to post this, put Im pretty new to this, so it would be great if it was spelled out better for me. Thanks!

1

There are 1 answers

5
Antarr Byrd On

If you are using Rails 4+ dynamic finders have been deprecated and extracted to a gem. The standard is now find_or_create_by or find_or_initialize_by.

def upvote 
    @post = Post.find (params[:id])
    session[:voting_id] = request.remote_ip
    upvote = Session.find_or_create_by(ip: session[:voting_id])
    @post.upvote
    redirect_to :back
end

def downvote  
  @post = Post.find (params[:id])
  session[:voting_id] = request.remote_ip
  downvote = Session.find_or_create_by(ip: session[:voting_id])
  @post.downvote
  redirect_to :back
end 

class Session < ActiveRecord::Base
  acts_as_voter
  request.remote_ip
end