url_for([:edit, @post])
正在工作并生成/comments/123/edit
。现在我需要添加一个查询参数,以便代替使用url_for查询参数?
/comments/123/edit
是
/comments/123/edit?qp=asdf
我试图url_for([:edit, @post], :qp => "asdf")
但没有去。
url_for([:edit, @post])
正在工作并生成/comments/123/edit
。现在我需要添加一个查询参数,以便代替使用url_for查询参数?
/comments/123/edit
是
/comments/123/edit?qp=asdf
我试图url_for([:edit, @post], :qp => "asdf")
但没有去。
使用命名路线。
edit_post_path(@post, :qp => "asdf")
您可以使用polymorphic_path
polymorphic_path([:edit, @post], :qp => 'asdf')
在轨道4,你可以这样做:url_for([[:edit, @post], :qp => "asdf"])
注意额外的数组语法。
来自Simone Carletti的answer确实有效,但有时候想要使用Rails路由指南中描述的对象构建URL,而不依赖于_path
帮助程序。
来自Ben和Swards的答案都试图描述如何做到这一点,但对我来说,使用的语法会导致错误(使用Rails 4.2.2,它的行为与4.2.4相同,这个答案的当前稳定版本)。
用于从对象创建URL /路径,同时也传递参数应该是,相对于嵌套排列,而包含URL组件以扁平阵列,加上一个散列作为所述最终元件的正确语法:
url_for([:edit, @post, my_parameter: "parameter_value"])
这里前两个元素被解析为URL的组件,并且哈希被认为是URL的参数。
这也适用于link_to
:
link_to("Link Text", [:edit, @post, my_parameter: "parameter_value"])
当我打电话url_for
的建议由本& Swards:
url_for([[:edit, @post], my_parameter: "parameter_value"])
我收到以下错误:
ActionView::Template::Error (undefined method 'to_model' for #<Array:0x007f5151f87240>)
跟踪表明,该正从polymorphic_routes.rb
称为ActionDispatch::Routing
,经由url_for
从routing_url_for.rb
(ActionView::RoutingUrlFor
):
gems/actionpack-4.2.2/lib/action_dispatch/routing/polymorphic_routes.rb:297:in `handle_list'
gems/actionpack-4.2.2/lib/action_dispatch/routing/polymorphic_routes.rb:206:in `polymorphic_method'
gems/actionpack-4.2.2/lib/action_dispatch/routing/polymorphic_routes.rb:134:in `polymorphic_path'
gems/actionview-4.2.2/lib/action_view/routing_url_for.rb:99:in `url_for'
的问题是,即它的预期URL组件的阵列(例如。符号,模型对象等),而不是包含另一个数组的数组。
望着从routing_url_for.rb
适当code,我们可以看到,当它接收具有哈希值作为最后一个元素的数组,它就会extract哈希和治疗作为参数,留下那么就阵列与URL组件。
这就是为什么具有作为最后一个元素的散列的平面数组工作,而嵌套数组没有。
我该如何创建一个绝对路径? – shredding 2013-11-22 12:25:42
使用_url而不是`_path`:`edit_post_url(@post,:qp =>“asdf”)` – 2013-11-22 16:26:31