简体   繁体   中英

Rails how to make example.com/post/1 to example.com/blog/post/1

I have a blog with root root 'posts#index'

And works best with example.com/ to example.com/posts

But what I want is something like this:

example.com/blog/posts/1 .

I've tried creating blog Controller and add

resources :blog do
resources :posts
end

But this is making my routes to blog/:id/posts/:id

If you don't have the relationship between the post and the blog as you mentioned, rails gives you the freedom to declare routes as our own.

so, to make the route example.com/posts/1 to, example.com/blog/posts/1 , just add a custom route at the last.

get '/blog/posts/:id', to: :show, controller: 'posts'

what this does is over rides the previous route and make this route final.

Now type rake routes and it will give the last route for you as,

GET /blog/posts/:id(.:format) posts#show

Now you can access using,

example.com/blog/posts/1

Reference for rails routing

Just to expand upon @Sravan answer. If you have multiple routes that will start with /blog/ you might want to check Rails guide on routing .

You can add something along the lines of

scope '/blog' do
    resources :posts
    resources :users
    resources :images
end

Which will create corresponding routes under /blog/.

namespace :blog do
  resources :posts
  resources :users
  resources :images
end

And your controller with namespace will look like this: Blog::PostsController

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