2010-05-07 98 views
1

當我在瀏覽器中訪問http://my-application.com/posts/1時,Rails知道我在尋找Postid = 1。我如何讓我的應用程序在內部執行此操作?也就是說,我想要一個函數(稱爲associate_with_resource),它接受一個包含URL作爲輸入的字符串並輸出關聯的資源。例如:在我的應用程序中將URL與資源相關聯

>> associate_with_resource('http://my-application.com/posts/1') 
=> #<Post id: 1, ... > 

(我想能夠使用associate_with_resource在我的應用程序,但 - 不僅在控制檯)當我在我的瀏覽器訪問http://my-application.com/posts/1

回答

0

,Rails的我知道正在尋找id爲1的帖子。

這是不正確的。

在Rails 3,當你把這個變成routes.rb

resources :posts 

然後Rails會知道你有一個文件app/controllers/posts_controller.rb名爲PostsController控制器。 Rails也會知道,在您的PostsController課程中,您有七種方法可用作動作方法:index,new,create,show,edit,update,delete

你在這些行動方法中所做的完全取決於你。您可能希望檢索並顯示Post對象,或者不顯示。

+0

我的錯誤。我想我正在尋找的是一種方法,將返回與給定路線相關的':controller'和':id'。從那裏我可以做一些像':controller.classify.constantize.find(:id)' – 2010-05-07 21:27:58

1

我想我在尋找ActionController::Routing::Routes.recognize_path方法

1

你是正確約ActionController::Routing::Routes.recognize_path,我會做這樣的:

創建一個文件lib/associate_with_resource.rb

module AssociateWithResource 
    def associate_with_resource(path) 
    url_hash = ActionController::Routing::Routes.recognize_path path 
    url_hash[:controller].classify.constantize.find(url_hash[:id]) 
    end 
end 

class ActionController::Base 
    include AssociateWithResource 
    helper_method :associate_with_resource 
end 

class ActiveRecord::Base 
    include AssociateWithResource 
end 

現在你可以調用從幾乎無處不在的associate_with_resource(path)獲取屬於給定路徑的資源

相關問題