Interacting with JSONB Columns Like an Active Record Resource
By Sandip Parida
Working with JSONB columns in your Active Record models doesn’t have to be messy. By leveraging the Active Model API, you can treat JSONB data with the same elegance as regular Active Record resources.
Why JSONB?
PostgreSQL’s JSONB is a binary JSON format that provides validation and faster processing. It’s perfect for storing configuration data, user preferences, and other semi-structured data alongside your regular model attributes.
Active Model to the Rescue
Active Model serves as the foundation for Active Record, and its modules can be used independently to add powerful features to plain Ruby objects.
Key Modules
ActiveModel::API
Adds validation capabilities to your JSONB-backed class:
class Pricing
include ActiveModel::API
validates :amount, presence: true
end
ActiveModel::Serialization
Provides serializable_hash for easy storage back to the JSONB column.
ActiveModel::Callbacks
Enables lifecycle hooks like before_save for tasks such as normalizing prices before persistence.
ActiveModel::Dirty
Tracks attribute changes — for example, restricting billing cycle modifications to the first of the month.
Putting It Together
The complete Pricing class combines all modules. The save method persists data to the parent Company model’s JSONB column, while update manages attribute assignment gracefully.
Conclusion
By combining Active Model modules, you can create rich, validated, trackable objects that live inside JSONB columns — giving you the flexibility of schemaless data with the safety of Active Record patterns.