Ruby on rails 如何为用户配置路由

Ruby on rails 如何为用户配置路由,ruby-on-rails,ruby,routes,Ruby On Rails,Ruby,Routes,我希望users#show操作在属性username下可用,而不是在用户id下可用 因此,如果我访问一个用户,我希望url显示类似于users/some\u username的内容,而不是users/22 我的路线: resources :users, only: %i(show edit update) do member do get :follows get :statistic get :my_topics, path: :to

我希望
users#show
操作在属性username下可用,而不是在用户id下可用

因此,如果我访问一个用户,我希望url显示类似于
users/some\u username
的内容,而不是
users/22

我的路线:

resources :users, only: %i(show edit update) do
      member do
        get :follows
        get :statistic
        get :my_topics, path: :topics
      end
    end

您可以向路由添加
param
选项

resources :users, param: :name, only: %i(show edit update) do
  member do
    get :follows
    get :statistic
    get :my_topics, path: :topics
  end
end
使用
rake routes | grep user
将产生以下结果

  follows_user GET      /users/:name/follows(.:format)     users#follows
statistic_user GET      /users/:name/statistic(.:format)   users#statistics
my_topics_user GET      /users/:name/topics(.:format)      users#my_topics
     edit_user GET      /users/:name/edit(.:format)        users#edit
          user GET      /users/:name(.:format)             users#show
               PATCH    /users/:name(.:format)             users#update
               PUT      /users/:name(.:format)             users#update

您可以向路由添加
param
选项

resources :users, param: :name, only: %i(show edit update) do
  member do
    get :follows
    get :statistic
    get :my_topics, path: :topics
  end
end
使用
rake routes | grep user
将产生以下结果

  follows_user GET      /users/:name/follows(.:format)     users#follows
statistic_user GET      /users/:name/statistic(.:format)   users#statistics
my_topics_user GET      /users/:name/topics(.:format)      users#my_topics
     edit_user GET      /users/:name/edit(.:format)        users#edit
          user GET      /users/:name(.:format)             users#show
               PATCH    /users/:name(.:format)             users#update
               PUT      /users/:name(.:format)             users#update

罗伯特的回答是:另一种方法是使用专门做这件事的宝石。许多选择之一可能是

其要点是向用户模型中添加一个字段(此处,
slug
,用于保存url段),该字段是在模型中生成的。对于获取记录,使用了一种方法,该方法可以像以前一样获取id,也可以获取slug

在您的情况下,除非您考虑对其他路由和模型具有相同的URL要求,否则这可能是过度的。


旁注:我与这个项目没有任何关联,我以前只使用过几次。

只是为了扩展nice,罗伯特的答案是:另一种方法是使用专门用于此目的的gem。许多选择之一可能是

其要点是向用户模型中添加一个字段(此处,
slug
,用于保存url段),该字段是在模型中生成的。对于获取记录,使用了一种方法,该方法可以像以前一样获取id,也可以获取slug

在您的情况下,除非您考虑对其他路由和模型具有相同的URL要求,否则这可能是过度的。


旁注:我与该项目没有任何关联,我以前只使用过几次。

您可以用
locolhost/users
替换
locolhost/username
,但不可能将成员路线替换为收集路线。也许,你可以用
locolhost/users/22
locolhost/username/22
顺便说一句:不要被否决票吓坏了,你的问题不太清楚,这就是为什么我编辑了这个问题,保持下去,但你可以试着在问题的语言上多做一些工作!祝你好运您可以将
locolhost/users
替换为
locolhost/username
,但无法将成员路由替换为收集路由。也许,你可以用
locolhost/users/22
locolhost/username/22
顺便说一句:不要被否决票吓坏了,你的问题不太清楚,这就是为什么我编辑了这个问题,保持下去,但你可以试着在问题的语言上多做一些工作!祝你好运您能否提供由
rake routes | grep user
定义的路由?您能否提供由
rake routes | grep user
定义的路由?