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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)