在Rails API响应中为未找到的记录获取原始SQL的一部分

问题描述 投票:0回答:2

我创建了一个config.api_only设置为true的Rails 5应用,并实现了一个控制器操作,该操作删除了作用域模型Message中的一条记录,问题是当我尝试删除一个不存在的记录时, ActiveRecord::RecordNotFound异常消息包含范围内使用的SQL查询的一部分,是否可能不在异常消息中包含该SQL?

型号代码:

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

控制器代码

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

如果发送错误的ID,我希望得到下一个响应:

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

但是相反,我收到此错误:

{
    "error": "Couldn't find Message with 'id'=23444 [WHERE \"message\".\"active\" = $1]"
}
ruby-on-rails activerecord ruby-on-rails-5 rails-api rails-models
2个回答
0
投票
据我所知,没有配置可以更改ActiveRecord::RecordNotFound异常错误消息。最好的办法是在没有范围的情况下获取消息,然后在执行销毁并返回适当的错误消息之前检查消息是否处于活动状态。

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


0
投票
我假设您在错误消息中看到SQL部分时,正在以“开发”模式运行应用程序。默认情况下,在“生产”模式下运行时,Rails将不再包含该信息。
© www.soinside.com 2019 - 2024. All rights reserved.