how to set up and use a Rails routes prefix

后端 未结 7 910
北海茫月
北海茫月 2021-02-05 07:39

When running rake routes I see:

 Prefix   Verb   URI Pattern                                       Controller#Action
 articles  GET    /articles(.:format)               


        
相关标签:
7条回答
  • 2021-02-05 08:17

    You're right, the prefix is used in building the named routes, so the resources method in the routes file creates routes like articles_path, new_article_path etc. To refer to a route in your code, add path to the prefix that you see when running rake routes.

    If you want to change the prefixes generated by the resources method in your routes file, use the :as option, like this:

    resources :articles, as: :posts

    This will generate routes like 'new_post_path' that you can use in your views.

    If you want to change the path of the route in the browser, you can use the path option:

    resources :articles, path: :posts
    

    Which will generate routes like /posts/1 or /posts/new instead of /articles/1 or /articles/new, but the routes will still be named articles_path, new_article_path etc in your code. You can use both :path and :as options to change both the path and the prefix of your resource routes.

    To change a basic route in your routes file, you can simply use :as, like so:

    get 'messages' => 'messages#index', as: :inbox

    This will create the route inbox_path which you can use in your code.

    Hope that helps!

    0 讨论(0)
提交回复
热议问题