ruby-on-rails 使用url_for?查询参数

siv3szwd  于 2023-02-26  发布在  Ruby
关注(0)|答案(4)|浏览(155)
url_for([:edit, @post])

正在运行并生成/comments/123/edit。现在我需要添加一个查询参数,以便代替

/comments/123/edit

它是

/comments/123/edit?qp=asdf

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

8aqjt8rx

8aqjt8rx1#

使用命名路由。

edit_post_path(@post, :qp => "asdf")
nszi6y05

nszi6y052#

您可以使用polymorphic_path

polymorphic_path([:edit, @post], :qp => 'asdf')
unftdfkk

unftdfkk3#

可以将params传递给url_for,在源代码中检查它:https://github.com/rails/rails/blob/d891c19066bba3a614a27a92d55968174738e755/actionpack/lib/action_dispatch/routing/route_set.rb#L675

9rnv2umw

9rnv2umw4#

Simone Carletti的answer确实可以工作,但是有时候需要使用Rails路由指南中描述的对象来构造URL,而不需要依赖_path helper。
BenSwards的答案都试图准确地描述如何执行此操作,但对我来说,使用的语法导致了一个错误(使用Rails 4.2.2,它与4.2.4具有相同的行为,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 #<Array:0x007f5151f87240>)
跟踪显示,这是从ActionDispatch::Routing中的polymorphic_routes.rb调用的,通过url_forrouting_url_for.rbActionView::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组件的数组。
这就是为什么以散列作为最后一个元素的平面数组有效,而嵌套数组无效。

相关问题