如何在没有设计的情况下设置acts_as_votable?

时间:2015-04-16 15:45:00

标签: ruby-on-rails ruby ruby-on-rails-4

我正在关注this post(我试图让人们在没有登录的情况下投票,1票/ ip)当我按下upvote按钮时,我收到以下错误:

   CommentsController中的NoMethodError #upvote undefined方法   对于#

,`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

1 个答案:

答案 0 :(得分:4)

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

确保sessions表格中有一个名为ip的列。

此外,首选的轨道4写作方式是:

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