【问题标题】:validates_each user_id & question_id stops collection of user_id but not creation of recordvalidates_each user_id & question_id 停止收集 user_id 但不创建记录
【发布时间】:2010-05-20 15:14:49
【问题描述】:

我试图限制我的应用程序的用户投票(在这种情况下喜欢)一个问题的答案特定次数。我成功地停止了 user_id 的收集,但记录不断被创建。我需要验证来实际阻止在 likes 表中创建记录。

alt text http://gadocidesign.squarespace.com/storage/Screen%20shot%202010-05-20%20at%2010.07.19%20AM.png

如您所见,最后两票丢失了 user_id 但仍被创建。下面的代码将向您展示我是如何做到这一点的。我试图限制用户对问题的任何答案投票不超过 10 次。

Like Model(我省去了反向的 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#create

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

【问题讨论】:

    标签: ruby-on-rails ruby validation activerecord


    【解决方案1】:

    您是在告诉它完全按照您所看到的那样做。

    # 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))
    

    【讨论】:

    • 完美。我不确定如何使用该合并功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 2015-03-20
    • 1970-01-01
    相关资源
    最近更新 更多