DEV Community

Discussion on: Rails 5.2.x --> Rails 6 counter_cache Gotcha

Collapse
 
6temes profile image
Daniel

Thanks for the insight!

Incidentally, apart from this precise case, I have never been able to decide when it is better to pass ActiveRecord an id, as in .where shelf_id: shelf.id, or the entire object .where shelf: shelf.

The second example seems more idiomatic, but I never knew when to favor one or the other.

By the way, I used the method where as an example, but it could be any other method that accepts an ActiveRecord instance or an id.

Collapse
 
loribbaum profile image
Lori Baumgartner

Totally agree! It's the one mystery of this change that I really want to investigate - because it's just not clear to me which to use when - and you're right, it's a decision we have to make in many other instances.

Collapse
 
asciigeek profile image
asciigeek

In most other ORM’s, in other frameworks, it is common to change those relationships using the entire object and not just setting the foreign key relationship with a primary key of a parent object. Clearly, rails has decided to go down that same avenue and it makes sense.

A proper framework should result in identically performing SQL whether you were specific in .where shelf_id: = shelf.id

or

.where shelf:=shelf

In the second case, the framework would understand that the primary key of shelf is ‘id’ and only utilize that one column in the query.

Collapse
 
swiknaba profile image
Lud

In an object oriented world, I believe we should pass objects around, not properties of objects. I guess that's what you mean with "idiomatic" already. Of course there are exceptions, e.g. when passing it to an asynchronously called worker, to avoid problems when dumping the payload into Redis as a json value, but usually you instantiate the object in said worker in the first line, to continue working with, well, objects.

Besides this, thank you for sharing your experience in this article, you're for sure not the only one running into this problem :-)