user6847053
user6847053

Reputation:

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

Upvotes: 0

Views: 105

Answers (3)

RAMKUMAR D
RAMKUMAR D

Reputation: 1

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

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

Upvotes: 0

42linoge
42linoge

Reputation: 26

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/.

Upvotes: 0

Sravan
Sravan

Reputation: 18647

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

Upvotes: 1

Related Questions