Best way to handle 404 in Rails3 controllers with a DataMapper get

邮差的信 提交于 2019-12-09 23:27:26

问题


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

With ActiveRecord I could have done this:

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

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

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

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


回答1:


I like to use exception throwing, and then use ActionController's rescue_from.

Example:

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:


Done 'the old Merb way':

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

again: It is possible to tell the controller to halt inside the not_found function instead of explicitly calling 'return false' in the show action?

edit: thanx to Francois that found a better solution:

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



回答3:


As DM documentation says, you can use #get!



来源:https://stackoverflow.com/questions/3515263/best-way-to-handle-404-in-rails3-controllers-with-a-datamapper-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!