views:

155

answers:

2

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?

+1  A: 

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.

j.
I guess this is the only way to go about it for now. Seems kind of roundabout though.
japancheese
A: 

Pass the user name as the input to the path helpers.

In your view code:

user_path(u.username) #/users/john

In your controller treat the id received as username:

def show
  user = User.find_by_username!(params[:id])
  ...
end
KandadaBoggu
That's kind of what I've been doing, but I just think it'd be more straightforward to do something like User.find_by_username(params[:username]) in the code. I really am just wondering why Rails doesn't allow this in general. Is it against some REST principle perhaps?
japancheese