处理中Rails3控制器404与DataMapper的获得最佳方式 [英] Best way to handle 404 in Rails3 controllers with a DataMapper get

查看:170
本文介绍了处理中Rails3控制器404与DataMapper的获得最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很简单,我想处理正常的[显示]请求,调用DataMapper的就像我在Merb的做到了。

It's very simple, I want to handle a normal [show] request with a call to DataMapper like I did in Merb.

使用ActiveRecord的,我可以这样做:

With ActiveRecord I could have done this:

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

和它通过捕获资源的例外处理404。

and it handles the 404 by catching the resource's exceptions.

DataMapper的,而不是不这样做自动所以现在我用这个解决方案解决它: [感动的答案]

DataMapper instead doesn't do this automatically so right now I'm solving it with this solution: [moved in the answers]

有可能告诉控制器停止NOT_FOUND函数里​​面?

It is possible to tell the controller to halt inside the not_found function?

推荐答案

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

I like to use exception throwing, and then use ActionController's 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

这篇关于处理中Rails3控制器404与DataMapper的获得最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆