url_for([:edit, @post])
目前代码可以工作并生成/comments/123/edit
。现在我需要添加一个查询参数,以便替换掉原先的
/comments/123/edit
这是
/comments/123/edit?qp=asdf
我尝试过url_for([:edit, @post], :qp => "asdf")
,但没有成功。
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')
polymorphic_url(event, locale: :fr)
,例如,我使用 url_for
时会得到 /Users/dorianmariefr/.rvm/gems/ruby-3.0.3/gems/actionpack-6.1.4.3/lib/action_dispatch/routing/route_set.rb:515:in
url_for': wrong number of arguments (given 2, expected 1) (ArgumentError)` 的错误。 - DorianSimone 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("链接文本", [: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>)
跟踪显示这是从polymorphic_routes.rb
中的ActionDispatch::Routing
被调用的,通过routing_url_for.rb
(ActionView::RoutingUrlFor
)中的url_for
:
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组件的数组。
这就是为什么具有哈希作为最后一个元素的平坦数组有效,而嵌套数组无效的原因。
_url
而不是_path
:edit_post_url(@post, :qp => "asdf")
- Simone Carletti