How to change a route name rails 4

Kevin Dark picture Kevin Dark · Apr 6, 2014 · Viewed 19.7k times · Source

I changed the routing of posts#index to match blog and I now get /blog in the URL which I was trying to accomplish.

I've tried several different things to get my actual blog post which the route currently looks something like /posts/this-is-a-test to also use blog rather than posts in the URL.
Below is my current route file. I am using the friendly_id gem, if that makes any difference in answering this question.

resources :posts do
  resources :comments
end

  resources :contacts, only: [:new, :create]

  root "pages#home"

  get "/home", to: "pages#home", as: "home"
  get "about" => 'pages#about'
  get "pricing" => 'pages#pricing'
  get "contact_us" => 'pages#contact_us'
  match 'blog', to: 'posts#index', via: :all
end 

Answer

kiddorails picture kiddorails · Apr 6, 2014

path option along with resource must help.

resources :posts, :path => 'blogs' do
  resources :comments
end

This will change all /posts and /post to /blogs/ and /blog.

If you want to change your route's helper methods such as posts_path to blogs_path and new_post_path to new_blog_path etc, you can change it with as tag.

resources :posts, :path => 'blogs', :as => 'blogs' do
  resources :comments 
end

Or yet better, you can specify the controller and route blogs directly as:

resources :blogs, controller: 'posts' do
  resources :comments
end

This is the awesomeness of Rails! :)