Writing my first monkey patch in rails

The motivation

From last few months we are facing an error which have become hard to replicate in development environment. The error is


ActiveRecord::JDBCError: org.postgresql.util.PSQLException: ERROR: missing FROM-clause entry for

This error occurs rarely and replicating have become hard. The idea was to log the query and see why the query is forming correctly.

Then I used, query.to_sql to log the query but this raise a new error


Unsupported argument type: NilClass. Construct an Arel node instead.

Now, i’m not even able to log the query directly, because to get query I have to use to_sql function which have some internal validation that throws an exception if the query is Invalid.


One of the feature that rails provide is monkey patch. Which allow us to override library functions and enable us to provide custom logic for these library function. I monkey patched StatementInvalid class to print the sql directly without validation.

module ActiveRecord
  class StatementInvalid < ActiveRecordError
    def initialize(message = nil, sql: nil, binds: nil)
      Sentry.capture_message("Invalid SQL Statement", :extra => { query: sql }) if Sentry.present? && sql.present?
      super(message || $!&.message)
      @sql = sql
      @binds = binds

    attr_reader :sql, :binds

This logs the sql which will enable us to find the root cause of wrong statement generation

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *