为什么这个Ruby on Rails代码不能像我想要的那样工作?

时间:2011-03-19 08:03:59

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord voting

所以我试图在这个问题中构建我所问的内容:Fix voting mechanism

但是,此解决方案不起作用。用户仍然可以多次投票他或她想要。我怎么能修复这个和/或重构?

def create       
    @video = Video.find(params[:video_id])
    @vote = @video.video_votes.new
    @vote.user = current_user

    if params[:type] == "up"
      @vote.value = 1
    else
      @vote.value = -1
    end

  if @previous_vote.nil?
    if @vote.save
      respond_to do |format|
        format.html { redirect_to @video }
        format.js
      end
    else
      respond_to do |format|
        format.html { redirect_to @video }
        format.js {render 'fail_create.js.erb'}
      end
    end
  elsif @previous_vote.value == params[:type]
    @previous_vote.destroy
  else
    @previous_vote.destroy    
    if @vote.save
      respond_to do |format|
        format.html { redirect_to @video }
        format.js
      end
    else
      respond_to do |format|
        format.html { redirect_to @video }
        format.js {render 'fail_create.js.erb'}
      end
    end
  end
  @previous_vote = VideoVote.where(:video_id => params[:video_id], :user_id => current_user.id).first
end

1 个答案:

答案 0 :(得分:3)

每个请求的开头

@previous_vote似乎都是零?

我个人会废除控制器中的所有逻辑,并在模型或数据库级别放置唯一性约束。

<强>更新

这可能充满了错误,但将其视为伪代码

模型类似于:

class Video < ActiveRecord::Base
  has_many :votes
end

class Vote < ActiveRecord::Base
  belongs_to :user
  belongs_to :video
  validates_uniqueness_of :user_id, :scope => :video_id # only one vote per person per video
end

class User < ActiveRecord::Base
  has_many :votes
end

控制器:

def create
  @video = Video.find(params[:video_id])
  @vote = current_user.votes.find_or_create_by_video_id(@video.id)

  # change this next block of code so you assign value to the vote based on whatever logic you need
  if you_need_to_do_anything_to_change_its_value
    @vote.value = :whatever
  end

  if @vote.save
    redirect_to @video
  else
    render :whatever_is_appropriate
  end
end