Matching and Routes in Rails

前端 未结 3 1982
南笙
南笙 2021-02-07 18:08

I generated a controller and changed the routes but opening the links yields errors on my local server.

Generating controller and routes



        
相关标签:
3条回答
  • 2021-02-07 18:17

    match method has been deprecated.

    Use get for GET and post for POST.

    get '/about', to: 'static_pages#about'

    0 讨论(0)
  • 2021-02-07 18:19

    First, you must specify the HTTP method by adding via: :get at the end of match 'st' => 'controller#action

    And it's better to use get '/home', to: 'static_pages#home'

    But, there is a problem, that your code doesn't follow RESTful, that only support 7 actions: index, new, edit, create, update, show and destroy.

    These are 2 solutions:

    SOL 1: Put them in different controller (homes, abouts..) and all of these controllers have action index.

    SOL 2: If it's too much work, we can match them to show action. We use static_pages controller, and each page (home, about) will be a item.

    The routes will look likes /static_pages/home /static_pages/about

    I know it isn't good because of the prefix static_pages.

    We can easily get rid of this by adding a custom routes at the end of routes file:

    get '/:id', to: 'static_pages#show'

    That's it. And if you think it's too much work (I think so too), check out this gem High Voltage. Have fun.

    0 讨论(0)
  • 2021-02-07 18:27

    You can use match, you've gotta add a via: option:

    match '/about',    to: 'static_pages#about', via: :get
    match '/team',     to: 'static_pages#team', via: :get
    match '/contact',  to: 'static_pages#contact', via: :get
    

    You can also pass other HTTP verbs to via: if you need to, like via: [:get, :post]

    Source: Rails Routing Guide

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