Matching and Routes in Rails

2019-03-18 17:29发布

问题:

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

Generating controller and routes

rails generate controller StaticPages home about team contact

Change routes.rb

MyApp::Application.routes.draw do
  root to: 'static_pages#home'

  match '/about',    to: 'static_pages#about'
  match '/team',     to: 'static_pages#team'
  match '/contact',  to: 'static_pages#contact'
end

The root path work but none of the 'about, 'team', or 'contact' links work. This is the error I get:

"You should not use the match method in your router without specifying an HTTP method. If you want to expose your action to both GET and POST, add via: [:get, :post] option. If you want to expose your action to GET, use get in the router: Instead of: match "controller#action" Do: get "controller#action""

Why can't I use 'match'?

回答1:

match method has been deprecated.

Use get for GET and post for POST.

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



回答2:

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



回答3:

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.