【问题标题】:Best way to handle 404 in Rails3 controllers with a DataMapper get使用 DataMapper get 在 Rails3 控制器中处理 404 的最佳方法
【发布时间】:2010-08-18 18:16:32
【问题描述】:

这很简单,我想像在 Merb 中一样通过调用 DataMapper 来处理正常的 [show] 请求。

使用 ActiveRecord 我可以做到这一点:

class PostsController
  def show
    @post = Post.get(params[:id])
    @comments = @post.comments unless @post.nil?
  end
end

它通过捕获资源的异常来处理 404。

DataMapper 不会自动执行此操作,所以现在我正在使用以下解决方案解决它: [在答案中移动]

可以在 not_found 函数中告诉控制器停止吗?

【问题讨论】:

标签: ruby-on-rails ruby activerecord ruby-on-rails-3 datamapper


【解决方案1】:

我喜欢使用异常抛出,然后使用ActionController的rescue_from

例子:

class ApplicationController < ActionController::Base
  rescue_from DataMapper::ObjectNotFoundError, :with => :not_found

  def not_found
    render file => "public/404.html", status => 404, layout => false
  end
end

class PostsController
  def show
    @post = Post.get!(params[:id]) # This will throw an DataMapper::ObjectNotFoundError if it can't be found
    @comments = @post.comments
  end
end

【讨论】:

    【解决方案2】:

    完成了“旧的 Merb 方式”:

    class ApplicationController
      def not_found
        render file: "public/404.html", status: 404, layout: false
      end
    end
    
    class PostsController
      def show
        @post = Post.get(params[:id])
        not_found; return false if @post.nil?
        @comments = @post.comments
      end
    end
    

    再次:可以告诉控制器在 not_found 函数内停止,而不是在 show 操作中显式调用“return false”吗?

    编辑:感谢 Francois 找到了更好的解决方案:

    class PostsController
      def show
        @post = Post.get(params[:id])
        return not_found if @post.nil?
        @comments = @post.comments
      end
    end
    

    【讨论】:

    • 这个答案在语法上是不正确的,但是如果已经渲染了某些东西,Rails 将停止自动渲染。如果@post.nil,你应该返回 not_found 吗?
    • 你是对的!返回 not_found 作品,感觉好多了。但是我的答案工作正常并且在语法上是正确的。无论如何感谢您的猜测,我将编辑答案
    【解决方案3】:

    As DM documentation says,你可以使用#get!

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 2016-01-24
      • 2020-06-24
      • 2010-10-11
      • 2013-09-15
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 1970-01-01
      相关资源
      最近更新 更多