我试图限制我的应用程序的用户投票(在这种情况下喜欢)一个特定次数的问题的答案。我成功停止了user_id的收集,但记录不断创建。我需要验证来实际阻止在likes表中创建记录。
正如您所看到的,最后两张选票失去了user_id但仍然创建了。下面的代码将向您展示我是如何做到这一点的。我试图限制用户在问题的任何答案上投票不超过10次。
和模型一样(我省略了反向的has_many关联,但它们就在那里)。
class Like < ActiveRecord::Base
belongs_to :site
belongs_to :user
belongs_to :question
validates_each :user_id do |row, attr, value|
m.errors.add :user_id, 'Too many likes' unless row.like_count < 10
end
def like_count
Like.count(:conditions => {:user_id => user_id, :question_id => question_id})
end
end
LikesController#创建
class LikesController < ApplicationController
def create
@user = current_user
@site = Site.find(params[:site_id])
@like = @site.likes.create!(params[:like])
@like.user = current_user
@like.save
respond_to do |format|
format.html { redirect_to @site}
format.js
end
end
end
答案 0 :(得分:0)
你告诉它要完全按照你所看到的去做。
# This is what creates the record you're seeing in your db.
@like = @site.likes.create!(params[:like])
# And now you try to assign the user.
@like.user = current_user
@like.save
尝试这样的事情:
@like = @site.likes.create!(params[:like].merge(:user_id => @user.id))