When working with Rails and PostgreSQL, we might encounter an issue where date columns are decoded as strings instead of Date objects.
The PostgreSQL adapter in Rails handles typecasting, but it falls short in parsing dates into Ruby Date objects, unlike the Mysql2 adapter which adeptly performs this task.
When direct SQL queries are used, the adapter doesn’t typecast date columns properly, so they are decoded as strings.
But with the recent changes in Rails 7.2, PostgreSQL Adapter now decodes columns of type date
to Date
instead of String
.
Before
In Rails, when using ActiveRecord::Base.connection.select_value
, the returned value will be a String
, even if the database column type is Date
.
This is because select_value
directly executes the SQL query
and returns the raw result from the database, without any type casting or conversion that would normally be done by ActiveRecord models.
After
Rails 7.2 added a Date decoder to the pg adapter to type cast dates at the connection level to type cast columns of type date
to Ruby Date
instead of String