Rails url_for named route with additional parameters

If I have a route with additional parameters, follow these steps:

match 'comments/new(/:post_id/(/:parent_id))' => 'comments#new'

Is there a clean way to create links for this named route? Obviously I can do:

link_to "New Comment", "comments/new/#{post_id}"

But I think there is a cleaner way. I just can't find the link in the url_for or link_to documentation.

+5
source share
1 answer

If you name a route, you can name it beautifully:

match 'comments/new(/:post_id/(/:parent_id))' => 'comments#new', :as => :new_comment

You can call it either with an options hash 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)
+16
source

All Articles