Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the id parameter in Rails routing

Using Ruby on Rails 3's new routing system, is it possible to change the default :id parameter

resources :users, :key => :username 

come out with the following routes

/users/new /users/:username /users/:username/edit ...etc 

I'm asking because although the above example is simple, it would be really helpful to do in a current project I'm working on.

Is it possible to change this parameter, and if not, is there a particular reason as to why not?

like image 932
joeellis Avatar asked May 14 '10 19:05

joeellis


People also ask

What is params ID in Rails?

params[:id] is meant to be the string that uniquely identifies a (RESTful) resource within your Rails application. It is found in the URL after the resource's name.

What is match in Rails routes?

Rails routes are matched in the order they are specified, so if you have a resources :photos above a get 'photos/poll' the show action's route for the resources line will be matched before the get line. To fix this, move the get line above the resources line so that it is matched first.

What is namespace in Rails routes?

This is the simple option. When you use namespace , it will prefix the URL path for the specified resources, and try to locate the controller under a module named in the same manner as the namespace.


2 Answers

In your route you can use

resources :user, param: :username 
like image 181
Ujjwal Thaakar Avatar answered Oct 20 '22 00:10

Ujjwal Thaakar


If I understand you correctly, what you want is to have the username instead of id in your url, right?

You can do that by overriding the to_param method in your model. You can get more information here.

like image 45
Ju Nogueira Avatar answered Oct 19 '22 22:10

Ju Nogueira