Search code examples
ruby-on-railsactiverecordruby-on-rails-5rails-apirails-models

Getting part of the raw SQL in Rails API response for not found records


I created a Rails 5 app with config.api_only set to true, and implemented a controller action that deletes a record in a scoped model Message the problem is that when I try to delete a record that doesn't exist, the ActiveRecord::RecordNotFound exception message includes part of the SQL query that is used in the scope, is possible to not include that SQL in the exception message?

Code of the model:

class Message < ActiveRecord::Base
  scope(:active) { where(active: true) }
end

Code of the controller

class MessageController < ApplicationController
  def delete
    message = Message.active.find(params[:id])
    begin
      message.destroy
      head :accepted # 202
    rescue ActiveRecord::RecordNotFound => error
      render json: { error: error.message }, status: 404
    end
  end
end

I would expect to get the next response if I send a wrong ID:

{
    "error": "Couldn't find Message with 'id'=23444"
}

But instead, I'm getting this error:

{
    "error": "Couldn't find Message with 'id'=23444 [WHERE \"message\".\"active\" = $1]"
}

Solution

  • As far as I know, there is no configuration to change the ActiveRecord::RecordNotFound Exception error message. The best thing you can do is fetch for the Message without the scope and then check if it's active or not before performing the destroy and return appropriate error message.

    class MessageController < ApplicationController
      def delete
        message = Message.find(params[:id])
        if message.active
          message.destroy
          head :accepted # 202
        else
          render json: { error: "Couldn't find Message with 'id'=#{params[:id]}" }, status: 404
        end
      rescue ActiveRecord::RecordNotFound => error
        render json: { error: error.message }, status: 404
      end
    end