If I have a route with optional parameters, as follows:
如果我有一个带有可选参数的路由,如下所示:
match 'comments/new(/:post_id/(/:parent_id))' => 'comments#new'
Is there a clean way to create the links for that named route? Obviously, I can do:
是否有一种干净的方法来为该命名路线创建链接?显然,我可以这样做:
link_to "New Comment", "comments/new/#{post_id}"
But I think there is a cleaner way. I just cannot find any reference in the url_for or link_to documentation.
但我认为有一种更清洁的方式。我只是在url_for或link_to文档中找不到任何引用。
1 个解决方案
#1
16
If you name the route, you can call it nicely:
如果您为路线命名,可以很好地调用它:
match 'comments/new(/:post_id/(/:parent_id))' => 'comments#new', :as => :new_comment
You can call it either with a hash of options, or an array in the correct order:
您可以使用选项哈希或正确顺序的数组来调用它:
link_to "New Comment", new_comment_path(:post_id => 1, :parent_id => 2)
link_to "New Comment", new_comment_path(1, 2)
#1
16
If you name the route, you can call it nicely:
如果您为路线命名,可以很好地调用它:
match 'comments/new(/:post_id/(/:parent_id))' => 'comments#new', :as => :new_comment
You can call it either with a hash of options, or an array in the correct order:
您可以使用选项哈希或正确顺序的数组来调用它:
link_to "New Comment", new_comment_path(:post_id => 1, :parent_id => 2)
link_to "New Comment", new_comment_path(1, 2)