【问题标题】:Rails: ActiveRecord::RecordNotFound exception the best way to handle the ExceptionRails:ActiveRecord::RecordNotFound 异常处理异常的最佳方式
【发布时间】:2015-09-17 09:22:23
【问题描述】:

我对 Rails 完全陌生。请帮助我。

我们可以处理这种异常的可能性有哪些。 因为 Rails 提供了多种选择来查找记录。但有时很难找到最好的。

所以

在此控制器中获取针对 id 的记录

class Api::ShowController < ApplicationController
      def get
        id = params[:id]
       # render json: id and return
        if id != nil
          @post = Post.find(id)
        else
          @posts = Post.all
        end
          render json: @posts
      end
    end

它显示:

Api::ShowController#get 中的 ActiveRecord::RecordNotFound

错误在这一行

@post = Post.find(id)

【问题讨论】:

  • 你应该遵守 REST 约定
  • 我是 ROR 的新手,你能推荐我的网页吗?
  • 标准的 Rails 方法是在您的控制器中为 CRUD(创建、查看、更新和删除)功能提供 7 个方法。这些被称为索引、显示、新建、创建、编辑、更新和销毁。欲了解更多信息,请在此处阅读guides.rubyonrails.org/routing.html

标签: ruby-on-rails activerecord


【解决方案1】:

看起来你必须做一些改变:

def get
  if params[:id].present?
    @post = Post.find_by(id: params[:id])
    if @post.nil?
      render json: { 
        :success => false,
        :message => "Post not found."
      }
    else
      render json: @post
    end
  else
    @posts = Post.all
    render json: @posts
  end
end

注意:对于 Rails 4,find_by_id 将在未来弃用,因此您必须使用 find_by(id: params id)。链接下方:

rails 4 deprecations

【讨论】:

    【解决方案2】:

    这意味着您的数据库中没有 ID 为 3 的 Post 记录。Post.find() 将在找不到具有请求的 ID 的帖子时返回错误。你可以改用Post.find_by_id(),它会返回一个空对象,但是你需要处理所有Post可以做而Nil不能做的事情。

    您可能希望在此处更改一些内容。

    • 未找到记录时的错误处理,当您要查找的帖子不存在时,您可能希望返回一些特定的 JSON。
    • 您正在创建@post 或@posts 这两个属性之一,但试图呈现@posts 的json 版本。如果找到帖子,这将是 nil。
    • 正如评论链中所讨论的,标准的 Rails 方法是使用 index 方法返回所有记录,并使用 show 方法返回单个记录。

    【讨论】:

    • 是的,它有效,我是否需要创建在index 操作中查找所有帖子的方法,以及在show 操作中显示单个帖子的新方法
    • 这是典型的 REST 方式,是的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    相关资源
    最近更新 更多