简体   繁体   中英

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 

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

match 'blog/:id' => 'posts#show'

should work. But if you want to match every method in posts controller to blog (and you don't want to use the posts path), I would just rename the controller to blog instead and add resource :blog in the routes.

这帮助我从官方指南文档中将其添加到您的routes.rb文件中:

get '/patients/:id', to: 'patients#show', as: 'patient'

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