Ruby on rails Rails路由,url中的用户名

Ruby on rails Rails路由,url中的用户名,ruby-on-rails,url,routing,Ruby On Rails,Url,Routing,我是Rails的新手,我正在开发一个应用程序,我想把用户名放在url中,Twitter风格 我有点像是在处理这个路由代码,但它很快变得非常丑陋,我现在在尝试删除时出错,因为帖子id丢失 必须有比这更好的方法来完成路线: get '/:username', to: 'users#index', as: :username get '/:username/posts', to: 'posts#index', as: :posts post '/:username/posts', to: 'posts

我是Rails的新手,我正在开发一个应用程序,我想把用户名放在url中,Twitter风格

我有点像是在处理这个路由代码,但它很快变得非常丑陋,我现在在尝试删除时出错,因为帖子id丢失

必须有比这更好的方法来完成路线:

get '/:username', to: 'users#index', as: :username
get '/:username/posts', to: 'posts#index', as: :posts
post '/:username/posts', to: 'posts#create', as: :create_post
delete '/:username/posts', to: 'posts#destroy', as: :delete_post
get '/:username/profile', to: 'profiles#index', as: :profile
patch '/:username/profile', to: 'profiles#update'
get '/:username/friends', to: 'friends#index', as: :friends
get '/:username/settings', to: 'settings#index', as: :settings
get '/:username/groups', to: 'groups#index', as: :groups
非常感谢您提供的任何建议。:)

更新:

在另一个问题上找到了这个。这似乎能让我达到我想去的地方。这能解决我的问题吗,还是我遗漏了什么

scope ":username" do
  get '', to: 'profiles#show'
  resources :posts
  resources :profile
  resources :friends
end

不建议使用,而应使用:

resources :users 
resources :profiles 
等等,因为它遵循RESTful结构。

考虑使用它提供现成的友好id/slug功能,因为在使用这种(友好id)方法时,可能会出现一些您自己没有考虑/测试的场景

此外,您的路线应如下所示:

resources :users, only: [:show, :index, ...] do
    resources :posts, only: :show
    resources :bars, only: [:show, :new]
end
和仅用于添加单个路由,而不用于嵌套资源。