views:

111

answers:

4

I have a relationship in my ActiveRecord based model that looks like:

belongs_to :foo

My model should always have foo defined in it for it to be valid. My question is, when using validates_presence of, which one is the appropriate one to use:

validates_presence_of :foo

or

validates_presence_of :foo_id

Assuming here of course, that foo_id is the appropriate foreign key, which it is by default if you do not change the association key.

+1  A: 

The first one: validates_presence_of :foo (though I think the second one will work too). In general the Ruby validation helpers work on model names as opposed to explicit column names. You can use this in addition to validates_associated to both validate the state of the associated entity in addition to its presence.

Richard Cook
+1  A: 

You may want to consider validates_associated

This will make sure that the association is valid.

The Who
validates_associated and validates_presence_of are mutually exclusive if I'm not mistaking. I want to make sure that the associated object is a part of the model. by definition, it should be valid itself.
randombits
You need to use both validates_associated and validates_presence_of. See other comment for link to documentation.
Richard Cook
A: 

neither - use validates_associated :foo

stephenmurdoch
but does validates_associated ensure that :foo is required/present in my model?
randombits
It doesn't validate that the `foo` is present. See documentation at http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html: "NOTE: This validation will not fail if the association hasn’t been assigned. If you want to ensure that the association is both present and guaranteed to be valid, you also need to use validates_presence_of."
Richard Cook
ahh, I always just presumed that they fixed the 'bug' which prevents validates_associated from doing what it really should do. Ryan Bates offers some thoughts [here](http://forums.pragprog.com/forums/74/topics/732)
stephenmurdoch
A: 

I use validates_presence_of :foo_id. It works.

antage