Reputation: 348
I'm following this post (I'm trying to let people vote without logging in, 1 vote/ip) and when I press the upvote button I'm getting the following error:
NoMethodError in CommentsController#upvote undefined method `find_or_create_by_ip' for #
Extracted source (around line #7):
5 @comment = Comment.find(params[:id]) 6 session[:voting_id] = request.remote_ip 7 voter = Session.find_or_create_by_ip(session[:voting_id]) 8 voter.likes @comment 9 flash[:message] = 'Thanks for voting!' 10 respond_to do |format|
I followed everything in the post, I created a Session model and added all the code to my files. Here is my code:
#routes.rb
Rails.application.routes.draw do
resources :posts do
resources :comments do
member do
post :upvote
end
end
end
root "posts#index"
end
#models:
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
acts_as_votable
end
class Session < ActiveRecord::Base
acts_as_voter
end
#controller:
class CommentsController < ApplicationController
before_action :set_post
def upvote
@comment = Comment.find(params[:id])
session[:voting_id] = request.remote_ip
voter = Session.find_or_create_by_ip(session[:voting_id])
voter.likes @comment
flash[:message] = 'Thanks for voting!'
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
def create
@comment = @post.comments.create(comment_params)
redirect_to root_path
end
def destroy
@comment = @post.comments.find(params[:id])
if @comment.destroy
flash[:success] = "Comment was deleted."
else
flash[:error] = "Comment could not be deleted."
end
redirect_to root_path
end
private
def set_post
@post = Post.find(params[:post_id])
end
def comment_params
params[:comment].permit(:content)
end
end
Upvotes: 3
Views: 373
Reputation: 13057
Session.find_or_create_by_ip(session[:voting_id])
is a dynamic attribute finder+builder method provided by Active Record, and it assumes that the sessions
table has a column named ip
.
Make sure the sessions
table has a column named ip
.
Also, the preferred rails 4 way of writing the same is:
Session.find_or_create_by(ip: session[:voting_id])
Upvotes: 4