2015-04-16 104 views
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 

回答

4

Session.find_or_create_by_ip(session[:voting_id])是活动记录提供一个dynamic attribute finder+builder方法,它假定sessions表中有一个名为ip列。

确保sessions表具有名为ip的列。

此外,编写相同的首选轨道4的方法是:

Session.find_or_create_by(ip: session[:voting_id]) 
+0

我加入了** ** IP列到会话表和编辑的行给你建议的内容。我仍然得到相同的错误:''未定义的方法'find_or_create'# – zazaalaza

+0

错字。它应该是'find_or_create_by'。您应该阅读我已包含的链接。 :-) –

+0

谢谢你的作品。实际上,当我创建会话模型时,我认为voting_id应该是会话表中的一列。我应该删除它吗? – zazaalaza

相关问题