0.0
The project is in a healthy, maintained state
Convert arrays of AR objects to Struct objects including virtual methods.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Development

~> 2.0
~> 13.0

Runtime

>= 6.0, < 9.0
>= 6.0, < 9.0
 Project Readme

better_pluck

Main purpose is to reduce loading into memory expensive ActiveRecord objects, where it is not needed (for read-only operations).

better_pluck adds struct_pluck, struct_pluck_with_display_name to ActiveRecord. These methods allow you to pluck not only database columns but also virtual methods and association data, returning lightweight Struct objects instead of heavy ActiveRecord instances.

This approach can reduce memory usage by up to 3-20x compared to loading full ActiveRecord objects.

Primary purpose: to be used in huge form dropdowns for select inputs.

Installation

Add this line to your application's Gemfile:

gem 'better_pluck'

Usage

Basic usage

You can pluck database columns and instance methods:

# Assuming Article has a method :name_on_site
articles = Article.struct_pluck(:id, :name, :email, :name_on_site)

articles.first.id           # => 1
articles.first.name_on_site  # => "My Article" (virtual method)

Associations

You can also pluck data from nested associations:

articles = Article.struct_pluck(
  :id,
  :name,
  author: [:name, :email, :display_name]
)

articles.first.author.email        # => "author@example.com"
articles.first.author.display_name # => "John Doe"

Pluck with Display Name

A convenience method specifically for dropdown lists and collections:

# Automatically includes :display_name for the model and associations
articles = Article.struct_pluck_with_display_name(:id, :name, author: [:name, :email])

articles.first.display_name         # => "Article Name"
articles.first.author.display_name # => "Author Name <author@example.com>"

select_with_joins method

You can use the select_with_joins method which will create field aliases for associations instead of fully fetching activerecord objects for them. The main model can be selected with specific columns or fully fetched. Main model is kept as ActiveRecord object.

# Example with positional arguments for base model
users = User.select_with_joins(:id, :name, organization: :name)
# SELECT users.id, users.name, organizations.name AS organization_name FROM users LEFT JOIN organizations ...
users.first.name              # => "John"
users.first.organization_name # => "Acme Corp"

# Example fetching all base model columns
articles = Article.select_with_joins(author: [:name])
# SELECT articles.*, authors.name AS author_name FROM articles LEFT JOIN authors ...
articles.first.author_name  # => "John Doe"