Rails 自定义和默认路由

Rails custom and default routes

我正在尝试为我的控制器定义自定义路由,我也需要使用一些默认路由。有什么简单的解决办法吗?

到目前为止我有这样的东西

resources :users do
  member do
    get 'users/:id', to: 'users#show'
    delete 'users/:id', to: 'users#destroy'
  end
  collection do 
    post 'users', to: 'users#create'
    post 'users/login', to: 'users#login'
  end
end
resources :users, :only => [:show, :destroy, :create, :login]

我不需要也不想要 index 路由,但使用此设置它仍在尝试将 GET users/ 路由到 user_controller index 方法。

我知道可能有一些简单明了的答案,但我找不到。

提前致谢。

您的第一行定义了索引操作的路径。仅定义一次资源。阅读 routing guide.

resources :users, :except => [:index] do
  collection do 
    post 'users/login', to: 'users#login'
  end
end

运行 rake routes 从项目根文件夹中的命令行查看所有路由定义。

你走错路线了。 resources :users 生成七个默认路由,其中​​也包括 index 路由。您需要将代码调整为以下

resources :users, :only => [:show, :destroy, :create] do
  collection do 
    post 'login', to: 'users#login'
  end
end

注:

如果您注意到了,我已经删除了 showcreatedelete 自定义路由 ,因为它们是默认生成的.