1

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?

makevoid
  • 3,276
  • 2
  • 33
  • 29
  • This is the best answer I've seen: http://stackoverflow.com/questions/2385799/how-to-redirect-to-a-404-in-rails/4983354#4983354 – Kelvin Aug 12 '11 at 21:18

3 Answers3

9

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
Ben Crouse
  • 8,290
  • 5
  • 35
  • 50
0

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
makevoid
  • 3,276
  • 2
  • 33
  • 29
  • 1
    This answer is syntactically incorrect, but Rails will stop automatic rendering if something already rendered. You should do return not_found if @post.nil? – François Beausoleil Aug 18 '10 at 19:17
  • You're right! return not_found works and it feels much better. But my answer is working properly and is syntactically correct. Anyway thanks for the guess, I'll edit the answer – makevoid Aug 19 '10 at 07:32
0

As DM documentation says, you can use #get!

Reactormonk
  • 21,472
  • 14
  • 74
  • 123