使用url_for查询参数?

ran*_*guy 30 ruby-on-rails query-parameters url-for ruby-on-rails-3

url_for([:edit, @post])
Run Code Online (Sandbox Code Playgroud)

工作和生成/comments/123/edit.现在我需要添加一个查询参数,以便代替

/comments/123/edit
Run Code Online (Sandbox Code Playgroud)

它是

/comments/123/edit?qp=asdf
Run Code Online (Sandbox Code Playgroud)

我试过url_for([:edit, @post], :qp => "asdf")但没有去.

Sim*_*tti 30

使用命名路由.

edit_post_path(@post, :qp => "asdf")
Run Code Online (Sandbox Code Playgroud)

  • 使用`_url`而不是`_path`:`edit_post_url(@ post,:qp =>"asdf")` (3认同)

epo*_*olf 21

您可以使用 polymorphic_path

polymorphic_path([:edit, @post], :qp => 'asdf')
Run Code Online (Sandbox Code Playgroud)


小智 10

Simone Carletti 的答案确实有效,但有时候人们想要使用Rails路由指南中描述的对象构建URL,而不是依赖于_path帮助程序.

BenSwards的答案都试图准确地描述如何做到这一点,但对我来说,使用的语法会导致错误(使用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按照Ben&Swards的建议打电话时:

url_for([[:edit, @post], my_parameter: "parameter_value"])

我收到以下错误:

ActionView::Template::Error (undefined method 'to_model' for #<Array:0x007f5151f87240>)

跟踪显示这是从polymorphic_routes.rbin ActionDispatch::Routing,url_forfrom 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'
Run Code Online (Sandbox Code Playgroud)

问题是,它期望一个URL组件数组(例如符号,模型对象等),而不是包含另一个数组的数组.

纵观适当的代码routing_url_for.rb,我们可以看到,当它接收具有哈希值作为最终的元素的数组,它就会提取哈希和治疗作为参数,然后留下刚与URL组件阵列.

这就是为什么带有散列作为最后一个元素的平面数组的工作原理,而嵌套数组则不然.