使用url_for查询参数?
url_for([:edit, @post])
正在工作和生成/comments/123/edit
。 现在我需要添加一个查询参数,以便代替
/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')
您可以将params
传递给url_for
。 在源代码中查看它: https : //github.com/rails/rails/blob/d891c19066bba3a614a27a92d55968174738e755/actionpack/lib/action_dispatch/routing/route_set.rb#L675
Simone Carletti的答案确实有效,但有时候人们想要使用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"])
当我按照Ben&Swards的建议调用url_for
:
url_for([[:edit, @post], my_parameter: "parameter_value"])
我收到以下错误:
ActionView::Template::Error (undefined method 'to_model' for #
跟踪显示这是从ActionDispatch::Routing
polymorphic_routes.rb
,通过来自routing_url_for.rb
url_for
( ActionView::RoutingUrlFor
) 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
的相应代码 ,我们可以看到,当它接收到一个以散列作为最终元素的数组时,它将提取散列并将其作为参数处理,然后只留下具有URL组件的数组。
这就是为什么带有散列作为最后一个元素的平面数组的工作原理,而嵌套数组则不然。
在rails 4中你可以这样做: url_for([[:edit, @post], :qp => "asdf"])
请注意其他数组语法。