Validates_uniqueness_of where scope euqals created_by "magic

I have the following ActiveRecord objects:

class Recipe < ActiveRecord::Base
has_many :ratings, :dependent => true
. . .
end

class Rating < ActiveRecord::Base
validates_uniqueness_of :created_by, :scope => :recipe_id
belongs_to :recipe, :counter_cache => true
. . .
end

The created_by field on Rating is implemented as a “magic” field
similar to this:
http://wiki.rubyonrails.org/rails/pages/Howto+Add+created_by+and+updated_by.
It is working fine.

The validates_uniqueness_of :created_by, :scope => :recipe_id isn’t
working. I can easily go about adding multiple Ratings per Recipe for a
user. Maybe I’m missing something here, but what I want is to make sure
that a user can only add one Rating per Recipe. I’m guessing that the
created_by field is null when the validation runs, and then is
populated by the current user when the record is saved. Can anyone shed
some light on this and perhaps point me to a better solution?

Thanks,

JB

Probably hack-ish, but you could manually set the created_by field
before you save.

Thanks. I tried that, but for some reason the validate doesn’t seem to
be running. I’m still getting duplicates.

If I add an index to the fields at the database level, then Rails
throws a duplicate record exception.

I wonder if it has something to do with one of my belongs_to
declarations. My entire Recipe model code looks like this:

class Rating < ActiveRecord::Base

validates_presence_of :recipe_id, :value
validates_numericality_of :value, :only_integer => true
validates_uniqueness_of :created_by, :scope => :recipe_id

belongs_to :recipe, :counter_cache => true
belongs_to :created_by, :class_name => “User”, :foreign_key =>
“created_by”

end