我有一个负责操纵资源路径的模型 . 如果可以的话,我想利用一些Rails路由助手 . 我不想对被操纵的资源类型做任何假设,因为我希望它是通用的 .
http://edgeguides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects说"You can also use url_for with a set of objects, and Rails will automatically determine which route you want:"
<%= link_to 'Ad details', url_for([@magazine, @ad]) %>
从我发现url_for帮助程序通常期望包含控制器,操作等的哈希 . 我一直在寻找的是上面的url_for似乎返回的内容,这是来自对象数组的资源路径 . 我不确定我是否只是使用了错误的命名空间,但通过API文档查找,我找不到提供上述方法的命名空间 .
只是为了澄清,我试图在模型中做下面的事情:
resource_array = [parent_resource, child_resource]
resource_path = url_for(resource_array)
我通常将任何路由代码保留在模型类之外,但此类专用于操作资源路径 . 提前致谢 .
Edit: 这是我最终使用的语法:
Rails.application.routes.url_helpers.polymorphic_path(resource)
Edit (2): 我觉得必须有一个更好的方法来做到这一点,但这就是我现在所拥有的 .
resource_path = ''
resource_array.each do |resource|
resource_path += '/' + resource.class.name.pluralize.underscore + '/' + resource.id.to_s
end
1 回答
我'm not sure this is what you'要求,但
url_for
是模块ActionDispatch::Routing::UrlFor
的实例方法,因此您需要extend
或include
该模块才能获得该方法的访问权限 .