randombits
randombits

Reputation: 48450

Ruby on Rails: question about validates_presence_of

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.

Upvotes: 11

Views: 2859

Answers (3)

antage
antage

Reputation: 1100

I use validates_presence_of :foo_id. It works.

Upvotes: 0

Richard Cook
Richard Cook

Reputation: 33089

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.

Upvotes: 8

The Who
The Who

Reputation: 6622

You may want to consider validates_associated

This will make sure that the association is valid.

Upvotes: 1

Related Questions