Mark Berry
Mark Berry

Reputation: 19102

Rails 3 link_to to add multiple dynamic parameters

In Rails 3.2.16, I've set up a route to #show a contact with a mandatory dynamic parameter. Another route includes a redirect default in case no parameter is specified.

routes rb (edited to show resources line)

resources :contacts, :except => :show
match 'contacts/:id' => redirect("/contacts/%{id}/from"), :via => "get"
match 'contacts/:id/:category' => 'contacts#show',
  :via => "get",
  :constraints => { :category => /from|to|about/ }

This

link_to "From", contact_path(@contact, :category => "to")

generates this link:

http://0.0.0.0:3000/contacts/1?category=to

In other words, it is correctly converting the :id to be part of the route, but it is then appending category as a separate parameter. The default route sees the path without :category and redirects it back to /contacts/1/from.

How can I write a link_to that will generate this HTML?

http://0.0.0.0:3000/contacts/1/to

Upvotes: 1

Views: 288

Answers (2)

Mark Berry
Mark Berry

Reputation: 19102

Stavros' answer works and may be the best solution. As another option, I realized that contact_path(@contact) is just returning a string, so without any modification to routes.rb, I can write

link_to "From", contact_path(@contact) + "/to"

Upvotes: 0

Ruby Racer
Ruby Racer

Reputation: 5740

In your routes.rb:

match 'contacts/:id/:category', :to => 'contacts#show',
    :via => "get",
    :constraints => { :category => /from|to|about/ },
    :as => :something

and then you call

link_to "From", something_path(@contact, "to")

Upvotes: 1

Related Questions