如何更改路由名称rails 4

Kev*_*ark 16 ruby-on-rails rails-routing ruby-on-rails-4

我改变了posts#index匹配的路由,blog现在我进入/blog了我想要完成的URL.

我已经尝试了几个不同的东西来获取我的实际博客文章,其中路线目前看起来/posts/this-is-a-test也像使用blog而不是posts在URL中.
以下是我当前的路线文件.我正在使用friendly_id宝石,如果这对回答这个问题有任何不同.

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 
Run Code Online (Sandbox Code Playgroud)

kid*_*ils 34

path 选项以及资源必须有所帮助.

resources :posts, :path => 'blogs' do
  resources :comments
end
Run Code Online (Sandbox Code Playgroud)

这将改变一切/posts,并/post/blogs//blog.

如果要更改路径的辅助方法(如posts_pathto blogs_pathnew_post_pathto new_blog_path等),可以使用as标记更改它.

resources :posts, :path => 'blogs', :as => 'blogs' do
  resources :comments 
end
Run Code Online (Sandbox Code Playgroud)

或者更好,您可以blogs直接指定控制器和路由:

resources :blogs, controller: 'posts' do
  resources :comments
end
Run Code Online (Sandbox Code Playgroud)

这是Rails的绝佳之处!:)

  • 如果你想将你的路径助手重命名为`blog`,你也会想要`as` (2认同)