3
我下面this post(我试图让人们投票,不登录,1票/ IP),当我按下按钮给予好评,我发现了以下错误:如何在没有设计的情况下设置acts_as_votable?
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|
我也跟着一切在帖子中,我创建了一个Session模型并将所有代码添加到我的文件中。这里是我的代码:
#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
我加入了** ** IP列到会话表和编辑的行给你建议的内容。我仍然得到相同的错误:''未定义的方法'find_or_create'# – zazaalaza
错字。它应该是'find_or_create_by'。您应该阅读我已包含的链接。 :-) –
谢谢你的作品。实际上,当我创建会话模型时,我认为voting_id应该是会话表中的一列。我应该删除它吗? – zazaalaza