How to fix Rails': TypeError: can't quote Hash

Find out is the solution for this exception in Ruby on Rails.
Published 2023-10-19 2 min read
How to fix Rails': TypeError: can't quote Hash

We often encounter error messages that leave us puzzled. One such error arises when the stack trace delves deeply into the intricate workings of ActiveRecord’s core, making it somewhat challenging to quickly discern the root cause.

This was the case for me today, as received a bug report from one of the systems. Unfortunately all I had was:

TypeError: can't quote Hash

This error is quite frustrating because the immediate line highlighted in the stack trace often looks something like this:

.../activerecord-<version>/lib/active_record/connection_adapters/abstract/quoting.rb

At its essence, this error conveys a basic mismatch. It’s signaling that, somewhere in your ActiveRecord query, you’ve used a Hash when the ActiveRecord anticipated a string (or something that can be coerced nicely into being a string). This minor oversight will result in this exact error.

A classic example that would trigger this error is when you use a query like:

YourModel.where(created_at: {date: 'yesterday'}).count

So, ensure you don’t use Hashes in places where simpler types are expected.

Identifying the problematic query isn’t always straightforward. Given that the backtrace for such errors is quite extensive, involves both ActiveRecord and Arel, you need to sift through it.

If you can rescue this error you should. Additionally print or log full stacktrace:

error.backtrace.join("\n")

The last line before entering ActiveRecord is a culprit.

#rubyonrails