简体   繁体   中英

Username in urls for nested routes

I'm a new rails developer making an application where I have a user profile like: localhost:3000/posts routing to localhost:3000/Charles where Charles is the username.

So the code I'm using to do this looks like:

routes.rb

match "/:username" => "posts#index"

and then in my controller:

@user = User.find_by_username params[:username]
@search = Post.search do |query|
    query.fulltext params[:search]
    query.with(:user, @user.id)
end

this works great just for the post index, but I'd like to have posts/18 (for example) be routed to /username/posts/18.

So basically, I'm asking if there's a way to do something like this:

match "/:username" => "posts#index" do
  resources :posts
end

Thanks for all help!

This

  scope '/:username' do
    resources :posts
  end

produces what you want:

    posts GET    /:username/posts(.:format)          posts#index
          POST   /:username/posts(.:format)          posts#create
 new_post GET    /:username/posts/new(.:format)      posts#new
edit_post GET    /:username/posts/:id/edit(.:format) posts#edit
     post GET    /:username/posts/:id(.:format)      posts#show
          PATCH  /:username/posts/:id(.:format)      posts#update
          PUT    /:username/posts/:id(.:format)      posts#update
          DELETE /:username/posts/:id(.:format)      posts#destroy

Try

scope ':username' do
  resources :posts
end

bundle exec rake routes

    posts GET    /:username/posts(.:format)          posts#index
          POST   /:username/posts(.:format)          posts#create
 new_post GET    /:username/posts/new(.:format)      posts#new
edit_post GET    /:username/posts/:id/edit(.:format) posts#edit
     post GET    /:username/posts/:id(.:format)      posts#show
          PUT    /:username/posts/:id(.:format)      posts#update
          DELETE /:username/posts/:id(.:format)      posts#destroy
match "/:username/posts/:id" => "posts#show"

But that won't really help when you need to edits and such. So, try:

scope "/:username" do
  resources :posts
end

That failing:

scope "/:username" do
  get '' => "posts#index"
  get 'posts/:id' => "posts#show"
end

Hopefully the first will work. Haven't tried it myself so forgive me, but I'm pretty sure that, in general, scope is what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM