代码之家  ›  专栏  ›  技术社区  ›  makevoid

使用DataMapper get处理Rails3控制器中的404的最佳方法

  •  1
  • makevoid  · 技术社区  · 14 年前

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

    有了ActiveRecord,我可以做到:

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

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

    [在答案中移动]

    有没有可能告诉控制器在not\u found函数中停止?

    3 回复  |  直到 14 年前
        1
  •  9
  •   Ben Crouse    14 年前

    我喜欢使用异常抛出,然后使用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
  •  0
  •   makevoid    14 年前

    做了“老默布的方式”:

    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\u found函数中停止,而不是在show操作中显式调用“return false”?

    编辑:thanx给Francois找到了更好的解决方案:

    class PostsController
      def show
        @post = Post.get(params[:id])
        return not_found if @post.nil?
        @comments = @post.comments
      end
    end
    
        3
  •  0
  •   Reactormonk    14 年前

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