Friday, November 20, 2009

[Rails] 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?

--
"Oh, look: rocks!"
-- Doctor Who, "Destiny of the Daleks"

--

You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate