views:

25

answers:

2

I have a User class and map.resources :users in my routes.

If I create a link

link_to @user.name, @user

It will somehow automatically create a link to /users/3 where 3 is an ID of the user. What if I want to create more userfriendly links and identify users not by IDs but by their usernames. So path would look like /users/some_user_name. How do I reassign the default link for @user so I wouldn't need to change all templates?

+1  A: 

You can use FriendlyId gem. This is exactly what you want. For example, if you want links look like /users/username:

class User < ActiveRecord::Base
  has_friendly_id :username
end
Voldy
Thanks it's a good solution, but I need to change it only for "show" action. The rest of actions should keep working with the normal ID. Otherwise, I'll have to change a lot of templates where sometimes I used @user.id instead of just @user
Arty
I believe there should be a way to just reassign default route for @user
Arty
It's easy to add route for only `show` action with `map.show_user 'users/:username', :controller => "users", :action => "show"` and exclude it from REST routes with `except`, but this is an additional headache. FriendlyId is the better practice. Only what you have to do you should disable user registration with usernames like your action's names, for example, `new`. By the way I'm curious why you want to keep `id` in other actions? Just interesting.
Voldy
A: 

Found it.

In User.rb:

def to_param
  username
end
Arty