I am trying to limit a user of my application to voting (liking in this case) a an answer to a question a particular number of times. I am successfully stopping the collection of the user_id but the record keeps getting created. I need for the validation to actually block the creation of the record in the likes table.
As you can see the last two votes lose the user_id but are still created. The code below will show you how I am doing this. I am trying to limit a user to voting no more than 10 times on any answer to a question.
Like Model (I spare you the reverse has_many associations but they are there).
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