Understanding “create_association” and i nvalid objects

The documentation on the “create_association” method of the “belongs_to”
association reads:

create_association(attributes = {})
Returns a new object of the associated type that has been instantiated with attributes, linked to this object through a foreign key, and that has already been saved (if it passed the validation).*

My expectation from this documentation is that calling
“object.create_association” will return the newly created object if both
objects save successfully and “false” if either object fails to save
(due to failed validations, for example); or throw an error.

My experience, however, is that “create_association” returns the newly
created object regardless of whether it saved successfully or not.

How can I catch and handle a situation where “create_association”
instantiates and links a new object but is unable to save it?

Rails 2.3.5


*ActiveRecord::Associations::ClassMethods

You received this message because you are subscribed to the Google
Groups “Ruby on Rails: Talk” group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.

On Fri, Dec 25, 2009 at 12:02 AM, Evan C. [email protected]
wrote:

and that has already been saved (if it passed the validation)

I think that “and that has already been saved (if it passed the
validation)” means only that the new object will only be saved if it
passed the validations, not that it won’t be instantiated in either
case.


Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: Rick DeNatale - Developer - IBM | LinkedIn

You received this message because you are subscribed to the Google
Groups “Ruby on Rails: Talk” group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.

the new object will only be saved if it
passed the validations, not that it won’t be instantiated in either
case.

How can I catch and handle a situation where this occurs (the new
object is instantiated, but not saved)?

You received this message because you are subscribed to the Google
Groups “Ruby on Rails: Talk” group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.