When working with activerecord I notice that while constructing associations, the reciprocal association is provided automatically only if the reciprocal model has already been saved. If it has not yet been saved, this reciprocal association must be defined manually. I am wondering if this is intentional or a bug, since the only difference in it working or failing is whether the reciprocal model has been saved or not.
I hopefully clarified this with the three scenarios described in the following gist.
I would expect Scenario 1 to work without the extra assignment step shown in Scenario 3. It doesn’t.
The reason is fairly simple – when you create an object through an association where the parent object is not yet saved, its associated foreign key can’t have a value, because the associated record isn’t saved yet. By means of example:
It’s a little unexpected, since you might logically expect Rails to keep the object association around and then assign the association foreign key at save-time, but it doesn’t seem to work that way.