validates :presence => association_name

Hi all,

Section 3.9 presence of the Active Record Validations and Callbacks guide states that

If you want to be sure that an association is present, you’ll need to test whether the foreign key used to map the association is present, and not the associated object itself.

class LineItem < ActiveRecord::Base belongs_to :order validates :order_id, :presence => true end

However, after a few tests, I now think this is not so. It seems that you may indeed validate de presence of an instance at the opposite end of an association, and that you may do this from either end of the association. Am I wrong? The Rails documentation does not help in this case.

Regards,

Manuel

When you’re doing something like this where a LineItem belongs_to an Order, then you would be validating that order_id is set when a LineItem is created. I think this is correct.

Could you provide an example of how you think it’s not correct?

I did not mean that the code was incorrect. It is the statement the accompanies the code that is incorrect, I think:

“If you want to be sure that an association is present, you’ll need to test whether the foreign key used to map the association is present, and not the associated object itself.”

Indeed, I think it is possible to write something like

class LineItem < ActiveRecord::Base

belongs_to :order validates :order, :presence => true end

which is much clearer, I think.

I don’t think that would do the same thing. You should be validating that the key is present, not that the object is present.

You are right, of course. My error. The validation in the code I sent just seems to work, if you don’t test it well enough.