Hi Colin,

After reading the API, I think that

     validates_presence_of   :user_id

will not even check to make sure that the user exists in the user
table.  It only makes sure that the field value is not blank:
http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_presence_of.

So this validation does not do the work of a proper foreign key
constraint.  Am I reading the API incorrectly?

Thanks.

On Jul 4, 2:14 am, Colin Law <[email protected]> wrote:
> 2009/7/4 Learn by Doing <[email protected]>:
>
>
>
>
>
> > If I have
>
> >   belongs_to  :user
>
> > Do I need to have
>
> >   validates_presence_of   :user_id
>
> > ?
>
> > Does Rails validate the presence of :user_id automatically if I have
> > belongs_to :user?
>
> > In other words, does Rails prevent against creating orphan records that
> > belong to non-existent users?
>
> I believe rails will not stop you creating a record with an empty
> user_id.  To be pedantic this is 'does not belong to any user' rather
> than 'belongs to a non-existent user' (for a non-existent user the
> user_id would contain a non-nil value for which there is no user).  In
> some applications this is a valid requirement.  If you wish to prevent
> this then include validates_presence_of as you have indicated.
>
> Colin
--~--~---------~--~----~------------~-------~--~----~
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 [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to