Thanks for the reply, @Betsy_Haibel.
Your idea is speaking to the concern I have. The thing I find surprising with ActiveRecord is that
post = Post.find(1000)
post.comments
will return an Array
post = Post.find(1000)
post.comments.to_a
also returns an Array
So it seems that to_a
needs to be more explicit, based on what developers are using it for.
Right now, I think developers are using to_a
as a way to avoid the objects in the child collection changing when accessing post.comments
multiple times.
post = Post.find(1000)
post.comments.first.object_id
post.comments.first.object_id
# The object_ids are different
The objects in the array get a new location in memory since they’re different objects. That’s what I think leads to confusion.
In the following case, post
represents a row in the db. However, accessing it multiple times does not change the object_id. comments
also represent rows in the db. Accessing it multiple times does, however, cause different object_ids.
post = Post.find(1000)
post.title
post.title
post.comments.first
post.comments.first
ORMs can be confusing regarding when the decide to re-query, which is not a problem that’s unique to ActiveRecord. The ORM makes decisions on when to re-query the db, so I believe it’s important to help the developer understand when the re-queries are going to happen, and how that affects the objects in memory. By naming methods in a more explicit way, such as using detatch
, the developer will have a better understanding of what ActiveRecord is doing.
Thanks for the discussion!