views:

37

answers:

1

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.

alt text

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
A: 

You're telling it to do exactly what you're seeing.

# 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

Try something like this instead:

@like = @site.likes.create!(params[:like].merge(:user_id => @user.id))
jdl
Perfect. I wasn't sure how to use that merge function.
bgadoci