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

mak*_*oid 1 ruby activerecord ruby-on-rails datamapper ruby-on-rails-3

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

使用ActiveRecord我可以这样做:

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

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

相反,DataMapper不会自动执行此操作,因此我现在正在使用此解决方案解决此问题:[在答案中移动]

有可能告诉控制器在not_found函数内停止吗?

Ben*_*use 9

我喜欢使用异常抛出,然后使用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
Run Code Online (Sandbox Code Playgroud)