validates :presence => association_name

65 views
Skip to first unread message

Manuel Menezes de Sequeira

unread,
Nov 18, 2011, 7:49:36 AM11/18/11
to rubyonra...@googlegroups.com
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

Ryan Bigg

unread,
Nov 21, 2011, 3:04:55 PM11/21/11
to rubyonra...@googlegroups.com
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?
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Documentation" group.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-docs/-/Ysm_V-iwPlUJ.
To post to this group, send email to rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-do...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-docs?hl=en.

Manuel Menezes de Sequeira

unread,
Nov 21, 2011, 8:05:52 PM11/21/11
to rubyonra...@googlegroups.com
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.

Ryan Bigg

unread,
Nov 21, 2011, 8:08:24 PM11/21/11
to rubyonra...@googlegroups.com
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 received this message because you are subscribed to the Google Groups "Ruby on Rails: Documentation" group.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-docs/-/YMO8oE7qymwJ.

Manuel Menezes de Sequeira

unread,
Nov 23, 2011, 12:19:12 PM11/23/11
to rubyonra...@googlegroups.com
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.
Reply all
Reply to author
Forward
0 new messages