Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a route name rails 4

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 
like image 312
Kevin Dark Avatar asked Apr 06 '14 07:04

Kevin Dark


People also ask

How do you define a route in Ruby?

The routing module provides URL rewriting in native Ruby. It's a way to redirect incoming requests to controllers and actions. It replaces the mod_rewrite rules. Best of all, Rails' Routing works with any web server.

What is namespace in Rails routes?

This is the simple option. When you use namespace , it will prefix the URL path for the specified resources, and try to locate the controller under a module named in the same manner as the namespace.


1 Answers

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! :)

like image 97
kiddorails Avatar answered Sep 22 '22 15:09

kiddorails