如何在没有设计的情况下设置acts_as_votable?
我正在关注这篇文章 (我试图让人们投票而不登录,1投票/ ip)当我按下upvote按钮时,我收到以下错误:
CommentsController中的NoMethodError #upvote未定义方法`find_or_create_by_ip’for#
提取的来源(第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|
我跟踪了post中的所有内容,创建了一个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提供的动态属性查找器+构建器方法,它假定sessions
表有一个名为ip
的列。
确保sessions
表有一个名为ip
的列。
此外,优选的轨道4写作方式是:
Session.find_or_create_by(ip: session[:voting_id])