首页 > 解决方案 > 如何让 Rails routes.rb 将多个路径重定向到单个控制器#action?

问题描述

我想知道是否有一种方法可以在 Rails 中使用“资源丰富的路由”来让所有路由都指向一个控制器#action。我希望 React Router 处理链接。

我已经查看了https://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use并发现了如何在 Rails 路由器之上使用 React 路由器(不使用 react-rails gem)?

我当前routes.rb的文件(这是实现此目的的最佳方法吗?):

Rails.application.routes.draw do
root to: "home#index"

  get 'games', to: 'home#index'
  get 'games/new', to: 'home#index'
  get 'games/:id', to: 'home#index'
  get 'games/:id/edit', to: 'home#index'

  namespace :api do
    resources :games
  end
end

标签: react-routerruby-on-rails-5.2

解决方案


  resources :games, controller: :home

这将为您提供所需的 crud 路径 + 索引。路径将是

/games
/games/new
/games/:id
/games/:id/edit

都指向HomeController

然后你仍然可以拥有命名空间的路由

更新: 根据 op 的评论更新答案


推荐阅读