ActiveRecord: only_columns

In Rails, we’ve always had ignored_columns to tell ActiveRecord: “Ignore these columns, even if they exist in the database.” But what if we want the opposite? What if we have a table with dozens of columns and our specific service only needs three?

The only_columns method allows for an “allowlist” approach to model attributes, giving you precise control over what data your application interacts with.

Inverting the Logic

There are two main scenarios where listing ignored columns becomes tedious:

  1. Shared Databases: When multiple applications share the same database, but a specific service should only “know” about its own relevant fields.
  2. Column Deprecation: The safe process of deleting a column usually involves ignoring it across all services first. If you have multiple microservices, you’d have to update every single one.

With only_columns, you define a strict contract. Instead of listing what you don’t want, you list exactly what the model is authorized to see. Anything not on this list is automatically ignored by ActiveRecord.

Example:

1
2
3
4
5
class User < ApplicationRecord
  # The model will only recognize these 3 columns, 
  # ignoring everything else in the table.
  self.only_columns = %w[id email created_at]
end

If a new secret_token column is added to the users table, this specific service won’t even realize it exists, ensuring data isolation and security.

A More Scalable Workflow

This feature is a major win for maintenance. If your service only uses 5 columns out of a 100-column table, you never have to update an “ignore list” again when other teams modify the schema. It provides security by omission, keeps objects in memory lighter, and makes your data contract explicit.