Rails Associations with unsaved records

I’m obviously still learning my way around Rails! Last night I found some problems with my project: it didn’t seem to be dealing with new associations properly. The problem was that the object I was adding associations to was unsaved, since it is one I build up in the session before committing.

It turned out that all I had to do was use build instead of create when adding the associated object. All of the create methods in Rails are really combined create-and-save – and you can’t save the association when at least one side is not saved itself.

In a way this reminds me of Joel’s Law of Leaky Abstractions. In cases like this, Rails makes it clear that you are using a fairly thin veneer over a database application, rather than an abstract OO system. You have to know how what you’re doing with ‘objects’ interacts with the database.

Post a Comment

Your email is never published nor shared. Required fields are marked *