Read more

Rails: Pluck across associated tables

Dennis
December 11, 2023Software engineer at makandra GmbH

#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"]]
Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

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.

Posted by Dennis to makandra dev (2023-12-11 09:57)