New gem to skip retrieving specified DB fields

The gem passive_columns for Rails 6.1+ that skips retrieving the specified columns by default (something like “default scope” with some columns selected, but works differently)

I know there are many talks around there about whether it’s good practice. Anyway, there are no alternatives alive so it might be useful for somebody.

Here is a small introduction.

  class Page < ApplicationRecord
    include PassiveColumns
    passive_columns :huge_article
  end


  page = Page.where(status: :active).to_a
  # => SELECT id, status, title FROM pages WHERE status = 'active'

  page = Page.select(:id, :title).take # => # <Page id: 1, title: "Some title">
  page.to_json # => {"id": 1, "title": "Some title"}
  
  # ______ Load a field only when needed______

  page.huge_article
  # => SELECT "pages"."huge_article" WHERE "pages"."id" = 1 LIMIT 1
  'Some huge article...'

  page.to_json # => {"id": 1, "title": "Some title", "huge_article": "Some huge article..."}

  # The next time you call the passive column it won't hit the database as it is already loaded.
  page.huge_article # => 'Some huge article...'
1 Like