Rails 路由,如何将用户名放在帖子前 url?

Rails Routing, how to put username before posts url?

我有这样的路线:

http://localhost:3000/posts/post-title

我想让我的路线是这样的:

http://localhost:3000/username/posts/post-title

有没有人可以教我怎么做?

谢谢

在routes.rb

1 =>

get '/:username/posts/:id', to: "controller#action", as: my_custom_route

这里你需要通过这个路径传递 2 个动态参数值 1 -> 用户名,2-> post_title

my_custom_route_path(username: username_value, id: post_title)

2 =>

如果您希望此操作的每个路由中的用户名都是静态的,那么

get '/username/posts/:id', to: "controller#action", as: :my_custom_route

这里只需要传一个动态参数就是post_title

my_custom_route(id: post_title)