首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails thumbs_up gem vote_exclusively_for

Rails thumbs_up gem vote_exclusively_for
EN

Stack Overflow用户
提问于 2011-08-08 20:09:05
回答 1查看 469关注 0票数 2

我目前正在使用thumbs_up gem来允许我的用户对帖子进行投票,并且在使用vote _exclusively_for/ and方法时遇到了问题。这里是gem的github链接:https://github.com/brady8/thumbs_up。gem可以很好地使用vote_up和vote_down方法,但当我将其更改为vote_exclusively_for时(它应该替换以前的否决和上升投票),我在开发日志中得到以下错误:

代码语言:javascript
复制
 ActiveRecord::RecordInvalid (Validation failed: Voteable has already been taken):
 app/controllers/posts_controller.rb:97:in `vote_up'

在启动新的投票之前,gem内部的一个方法似乎没有清除前一次投票。下面是我在posts_controller中的代码:

代码语言:javascript
复制
  def vote_up
    @user = current_user
    @post = Post.find(params[:id])
    @user.vote_exclusively_for(@post)
    redirect_to (..)
 end

以下是gem中的代码:

代码语言:javascript
复制
  def vote_exclusively_for(voteable)
    self.vote(voteable, { :direction => :up, :exclusive => true })
   end

 def vote(voteable, options = {})
    raise ArgumentError, "you must specify :up or :down in order to vote" unless options[:direction] && [:up, :down].include?(options[:direction].to_sym)
    if options[:exclusive]
     self.clear_votes(voteable)
    end
    direction = (options[:direction].to_sym == :up)
    Vote.create!(:vote => direction, :voteable => voteable, :voter => self)
  end

 def clear_votes(voteable)
    Vote.where(
      :voter_id => self.id,
      :voter_type => self.class.name,
      :voteable_id => voteable.id,
      :voteable_type => voteable.class.name
    ).map(&:destroy)
  end

我不确定为什么clear_votes方法没有删除前一次投票。任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-08-08 20:58:49

尝试在控制台中运行此命令,看看它是否正常工作:

代码语言:javascript
复制
user = ... # fetch the right user
post = ... # fetch the right post

Vote.where(
  :voter_id => user.id,
  :voter_type => User,
  :voteable_id => post.id,
  :voteable_type => Post
).map(&:destroy)

您还可以临时编辑clear_votes并在那里做一些日志记录,以确保self.class.namevoteable.class.name引用了正确的类。另外,在映射到destroy命令之前,使用count记录where方法调用,以确保它不会返回空数组。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6981859

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档