我正在关注这篇文章(我试图让人们在不登录的情况下进行投票,每次投票1 ip),当我按下upvote按钮时,出现以下错误:
评论控制器中的NoMethodError #upvote#的未定义方法`find_or_create_by_ip'
提取的源(第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
Session.find_or_create_by_ip(session[:voting_id])
是Active Record提供的动态属性finder + builder方法,它假定该sessions
表具有名为的列ip
。
确保该sessions
表具有名为的列ip
。
同样,首选的rails 4编写方式是:
Session.find_or_create_by(ip: session[:voting_id])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句