This week at work I was disappointed to find that calling #new on an association collection doesn’t add the new instance to the cached collection:

>> patrick = Poster.first=> #>> patrick.posts.size=> 0

>> new_post = patrick.posts.new(:title => "Another post")=> #

>> patrick.posts.size=> 0

If I like the post and decide to save it to the database, my cached posts still doesn’t get updated:

>> new_post.save=> true

>> patrick.posts.size=> 0

In order to get the collection up-to-date I have to know that this is a trouble spot, and call #reload on the association:

>> patrick.posts.reload; patrick.posts.size=> 1

If, instead, I try to push that new instance onto the collection explicitly, it gets saved automatically, which doesn’t seem very intuitive (I *much* prefer to have to explicitly save changes to the database):

eee.c — Well, you’re certainly right about there being a difference between size/length/count.

I was using #size here for brevity, but it looks like I glossed over the fact that the underlying issue here is what is getting cached. It isn’t the count (#length and #size return the same in my examples), but rather the array of associated elements getting cached.

For the #new example, despite the instantiated object having the correct poster_id, it doesn’t get added to patrick’s cached collection of posts. So, calling “patrick.save” doesn’t trigger the save of new_post, and a subsequent call to patrick.posts.length (or size) doesn’t represent the new_post we intended to create.