私は現在、ユーザーが投稿に投票できるようにthumbs_up gemを使用していますが、vote_exclusively_for/againstメソッドで問題が発生しています。宝石のギブスリンクはhttps://github.com/brady8/thumbs_upです。宝石はvote_upとvote_downメソッドでうまく動作しますが、vote_exclusively_forに変更すると(開発中の前回の投票を置き換える予定です)、開発ログに次のエラーが表示されます:Rails thumbs_up gem vote_exclusively_for
ActiveRecord::RecordInvalid (Validation failed: Voteable has already been taken):
app/controllers/posts_controller.rb:97:in `vote_up'
宝石の中のメソッドは、新しい投票を開始する前に前回の投票をクリアしていないようです。ここに私のコードはposts_controllerである:
def vote_up
@user = current_user
@post = Post.find(params[:id])
@user.vote_exclusively_for(@post)
redirect_to (..)
end
ここでは宝石のコードは次のとおりです。
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方法は、以前の投票を削除されていない理由を私はよく分かりません。どんな助けでも大歓迎です。
私はあなたが私を正しい方向に向けると信じています。私はポストの2つの異なるクラスがありますので、投稿のための単一テーブルの継承セットアップがあります。私は:voteable_typeは、継承されたクラスのいずれかに設定されていると思うが、私は投票テーブルの親クラスに設定している。ありがとうございました! – roobnoob
あなたは大歓迎です!喜んで助けた! :) – Behrang