2010-08-18 56 views
1

這很簡單,我想通過調用DataMapper來處理正常的[show]請求,就像我在Merb中那樣。使用DataMapper處理Rails3控制器中的404的最佳方法獲取

用ActiveRecord我可以這樣做:

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

,它通過捕獲資源的例外處理404。

DataMapper的,而不是不這樣做自動所以現在我有這個解決方案解決它: [感動的答案]

它可以告訴控制器的NOT_FOUND函數內停止?

+0

這是最好的答案,我已經看到了: http://stackoverflow.com/questions/2385799/how-to-redirect-to-a-404-in- rails/4983354#4983354 – Kelvin 2011-08-12 21:18:37

回答

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 
+0

真棒解決方案,謝謝! – makevoid 2011-05-16 13:46:43

0

完成「老Merb的方式」:

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 
再次

:它可以告訴控制器到NOT_FOUND函數內部停止,而不是顯式調用在表演行動「返回false」?

編輯:感謝名單弗朗索瓦遇見一個更好的解決方案:

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

這個答案在語法上是不正確的,但是如果已經呈現,Rails將停止自動呈現。你應該做 如果@ post.nil返回not_found? – 2010-08-18 19:17:03

+0

你是對的!返回not_found的作品,感覺好多了。但是我的回答正常,語法正確。無論如何感謝猜測,我會編輯答案 – makevoid 2010-08-19 07:32:07

相關問題