2015-04-16 135 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

相關問題