Rails: Pluck across associated tables

Posted 5 months ago. Visible to the public. Repeats.

#pluck is commonly used as a performant way to retain single database values from an ActiveRecord::Relation

Book.pluck(:title, :price) #=> [["The Hobbit", "8.99"], ["The Alchemist", "7.89"]]

But #pluck can do more: you can query multiple tables as well!

Book.joins(:author).pluck("books.title, books.price, authors.name") #=> [["The Hobbit", "8.99", "J. R. R. Tolkien"], ["The Alchemist", "7.89", "Paulo Coelho"]]

Note the use of :author for the joins, and then authors for the pluck clause. The first corresponds to the belongs_to relationship, and the latter is the name of the db table.

You could even write the code as follows. As long as the names of the columns are unique, the active record query interface will be able to assign them to the correct model:

Book.joins(:author).pluck(:title, :price, :name) #=> [["The Hobbit", "8.99", "J. R. R. Tolkien"], ["The Alchemist", "7.89", "Paulo Coelho"]]

However, I would prefer the first option, as you can see where the values come from.

Dennis
Last edit
5 months ago
Dennis
License
Source code in this card is licensed under the MIT License.
Posted by Dennis to makandra dev (2023-12-11 08:57)