开发者

Rails: how to create a default route for specific object

开发者 https://www.devze.com 2023-01-16 22:16 出处:网络
I have a User class andmap.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.

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 thei开发者_开发技巧r 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?


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


Found it.

In User.rb:

def to_param
  username
end
0

精彩评论

暂无评论...
验证码 换一张
取 消