2010-05-07 38 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)获取属于给定路径的资源

相关问题