Slick23
Slick23

Reputation: 5897

Nested routes (and constraints)

This is what I'm using in my routes.rb file

  match 'trackers/(:token)' => 'trackers#show' 

  resources :trackers do
    resources :locations
  end

Is there anyway to nest :locations under the match statement, so the URL for locations will use the tracker's token (which is an string of letters and numbers six long), instead of using the tracker's id? Also, I want the match statement to work no matter the case of the characters in the URL ... all the tokens start with 1X, but if someone types 1x I still want it to work. I can't seem to decipher the syntax/regular expression that would make that work.

Upvotes: 0

Views: 213

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124419

You can get around all this by simply adding a to_param method to your Tracker model:

def to_param
  token
end

Then you can get rid of your match statement altogether. All links generated using tracker_path(tracker), edit_tracker_path(tracker), etc. will automatically use your token field.

However, keep in mind that even though it's using the token field, your forms will still submit the value as params[:id], not params[:token].

Upvotes: 2

Related Questions