Watch out when chaining does not return original object

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the dumb-mistakes-and-gotchas category.

Last Updated: 2024-11-21

This method chain failed on me due to me making a silly mistake

product = Product.find(id).update!(alternate_names: Array.wrap(list_of_names))
product.name

Why? Although Product.find() returns an instance of Product, the call to update immediately afterwards returns true/false, not the product.

The fix was to move the method (update) that changed the return type from Product to boolean to another line so as not to interfere with the assignment to product.

product = Product.find(id)
product.update!(alternate_names: Array.wrap(list_of_names))
product.name

Lesson

When assigning the result of chaining methods, always asks yourself "will the return type be what I am expecting for this variable?"

Often it's better to err on the side of caution and separate the assigning from the chaining.