我目前正在使用thumbs_up gem来允许我的用户对帖子进行投票,并且在使用vote _exclusively_for/ and方法时遇到了问题。这里是gem的github链接:https://github.com/brady8/thumbs_up。gem可以很好地使用vote_up和vote_down方法,但当我将其更改为vote_exclusively_for时(它应该替换以前的否决和上升投票),我在开发日志中得到以下错误:
ActiveRecord::RecordInvalid (Validation failed: Voteable has already been taken):
app/controllers/posts_controller.rb:97:in `vote_up'在启动新的投票之前,gem内部的一个方法似乎没有清除前一次投票。下面是我在posts_controller中的代码:
def vote_up
@user = current_user
@post = Post.find(params[:id])
@user.vote_exclusively_for(@post)
redirect_to (..)
end以下是gem中的代码:
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方法没有删除前一次投票。任何帮助都将不胜感激。
发布于 2011-08-08 20:58:49
尝试在控制台中运行此命令,看看它是否正常工作:
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.name和voteable.class.name引用了正确的类。另外,在映射到destroy命令之前,使用count记录where方法调用,以确保它不会返回空数组。
https://stackoverflow.com/questions/6981859
复制相似问题