为什么这个Ruby on Rails代码不能像我想要的那样工作?
所以我试图在这个问题中构建我所问的内容: 修复投票机制
但是,此解决方案不起作用。 用户仍然可以多次投票他或她想要。 我怎么能修复这个和/或重构?
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
@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
- Railsvalidation以确保用户名不会与现有路由冲突?
- 在Rails应用程序中的查询运行时更改表名
- 通过rails中的多个条件查找
- Rails应用程序错误 – ActiveRecord :: PendingMigrationError正在等待迁移; 运行’rake db:migrate RAILS_ENV = development’来解决此问题
- 质量分配exception没有找到解释(Rails 3.2.1)
- 获取Rails ActiveRecord’datetime’属性作为DateTime对象
- Rails安全性:完全避免批量分配
- Rails:如何获取深度为2’has_many’级别的记录?
- Rails:使用“attributes”方法将属性从对象复制到另一个对象