Ensuring that foreign key is valid

I am trying to set up a validation in a model to ensure that a record can't be saved unless the foreign key it belongs_to is a valid record. My model says:

    class Admin < ActiveRecord::Base   validates_presence_of :user_id   validates_numericality_of :user_id   validates_uniqueness_of :user_id   validates_associated :user

  belongs_to :user

    end

but I can still create an admin record even if the associated user record doesn't exist. I tried creating a custom validator, too, but I couldn't test User.find(@user_id) from within the model.

How can I check for this at the model level?

Did you look at validates_associated

http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M002171

Darian Shimy

Yes, didn't you see it included in the original post? Of course, that doesn't mean it's being used correctly, or that the bug isn't somewhere else. Even when calling save!, all I get is a terse message saying that the user can't be validated.

Is there a way to force the test to be more verbose when evaluating validations, especially those which take place in other models? I'm at a bit of a loss to understand why a simple 'validates_associated :user' doesn't work, but I'll bet a more detailed trace would shine a light on it.

> Did you look at validates_associated Is there a way to force the test to be more verbose when evaluating validations, especially those which take place in other models? I'm at a bit of a loss to understand why a simple 'validates_associated :user' doesn't work, but I'll bet a more detailed trace would shine a light on it.

Well as the docs say, "This validation will not fail if the association hasn‘t been assigned". validates_presence_of :user should do the truck (but if you want a cast iron guarantee, use a foreign key constraint)

Fred