Best way to handle 404 in Rails3 controllers with

2020-07-31 19:16发布

问题:

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!