Ruby on Rails

Viewing the raw database attributes from your Rails model


Sometimes a lot of things happen inside your Rails model instance that transform the values from the database, for example using after_initialize callbacks.

When you’re debugging it can be nice to see what actual data you get from the database. You can directly go to your database using the CLI or a nice GUI tool, but you can also use your trusted old Rails console.

Rails keeps around the ActiveRecord::AttributeMethods::BeforeTypeCast module, which has all the tools you need.

task = Task.new(completed_on: "2020-06-10")

task.completed_on
# => Wed, 10 Jun 2020

task.attributes_before_type_cast
# => { "completed_on" => "2020-06-10", ... }
task.read_attribute_before_type_cast("completed_on")
# => "2020-06-10"

You can also use dynamic finders which are so common in Rails:

task.completed_on_before_type_cast
# => "2020-06-10"

This also works the other way around, when setting attributes you can get the unprocessed value using the same methods:

task = Task.new(completed_on: "2020-06-10")

task.read_attribute("completed_on")
# => Wed, 10 Jun 2020
task.read_attribute_before_type_cast("completed_on")
# => "2020-06-10"

This helped me understand one of our models, which does encryption and decryption inside callbacks, a bit better.