Rails link_to action with URL parameters

2019-09-06 23:52发布

问题:

If I have a route like so

get 'controller/:id/action/:param' => 'Controller#action'

How can I use link_to to create a link like <a href="/controller/12345/action/abcde">?

So far I have gotten link_to 'Link text', {:action => 'action'}

To give me <a href="/controller/12345/action">

but using link_to 'Link text', {:action => 'action', :param => 'abcde'}

will give me <a href="/controller/12345/action?param=abcde">

回答1:

You can name your route:

get 'controller/:id/action/:param' => 'Controller#action', :as => 'custom_show'

This should give you a new url helper which you can use like this:

<%= link_to "Foobar", custom_show_path(:id=>1234, :param=>'my_param') %>