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.
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