Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails url_for named route with optional parameters

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.

like image 388
berkes Avatar asked Mar 11 '11 11:03

berkes


1 Answers

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)
like image 187
idlefingers Avatar answered Nov 03 '22 20:11

idlefingers