如何在没有设计的情况下设置acts_as_votable? [英] How to set up acts_as_votable without devise?

查看:55
本文介绍了如何在没有设计的情况下设置acts_as_votable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注 这篇文章(我试图让人们在不登录的情况下投票,1 票/ip),当我按下 upvote 按钮时,我收到以下错误:

I'm following this post (I'm trying to let people vote without logging in, 1 vote/ip) and when I press the upvote button I'm getting the following error:

CommentsController 中的 NoMethodError#upvote 未定义方法`find_or_create_by_ip' #

NoMethodError in CommentsController#upvote undefined method `find_or_create_by_ip' for #

提取的源代码(围绕第 7 行):

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|

我遵循了帖子中的所有内容,创建了一个会话模型并将所有代码添加到我的文件中.这是我的代码:

I followed everything in the post, I created a Session model and added all the code to my files. Here is my code:

#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]) 是一个 动态属性查找器+构建器方法记录,并假设 sessions 表有一个名为 ip 的列.

Session.find_or_create_by_ip(session[:voting_id]) is a dynamic attribute finder+builder method provided by Active Record, and it assumes that the sessions table has a column named ip.

确保 sessions 表有一个名为 ip 的列.

Make sure the sessions table has a column named ip.

另外,rails 4 的首选写法是:

Also, the preferred rails 4 way of writing the same is:

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

这篇关于如何在没有设计的情况下设置acts_as_votable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆