views:

31

answers:

3

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?

A: 

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
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
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
A: 

As DM documentation says, you can use #get!

Tass
+1  A: 

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