Rails路由:GET没有param:id

我正在开发基于rails的REST api。 要使用这个API,你必须登录。关于这一点,我想在我的用户控制器中创建一个方法,它将返回登录用户信息的json。 所以,我不需要在URL中传递:id 。 我只想打电话给http://domain.com/api/users/me

所以我尝试了这个:

 namespace :api, defaults: { format: 'json' } do scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do resources :tokens, :only => [:create, :destroy] resources :users, :only => [:index, :update] do # I tried this match 'me', :via => :get # => api_user_me GET /api/users/:user_id/me(.:format) api/v1/users#me {:format=>"json"} # Then I tried this member do get 'me' end # => me_api_user GET /api/users/:id/me(.:format) api/v1/users#me {:format=>"json"} end end end 

正如你所看到的,我的路线等待身份证,但我想得到像设计一样的东西。 基于current_user id的东西。 示例如下:

 edit_user_password GET /users/password/edit(.:format) devise/passwords#edit 

在此示例中,您可以编辑当前用户密码,而无需将id作为参数传递。

我可以使用集合而不是成员,但这是一个肮脏的旁路……

有人有想法吗? 谢谢

资源路由旨在以这种方式工作。 如果你想要不同的东西,可以自己设计,就像这样。

 match 'users/me' => 'users#me', :via => :get 

把它放在你的resources :users之外resources :users阻止

要走的路是使用奇异的资源 :

所以,而不是resources使用resource

有时,您拥有一个客户端总是在不引用ID的情况下查找的资源。 例如,您希望/ profile始终显示当前登录用户的配置文件。 在这种情况下,您可以使用单一资源将show / profile(而不是/ profile /:id)映射到show动作[…]

所以,在你的情况下:

 resource :user do get :me, on: :member end # => me_api_user GET /api/users/me(.:format) api/v1/users#me {:format=>"json"} 

也许我错过了什么,但你为什么不使用:

 get 'me', on: :collection 
  resources :users, only: [:index, :update] do collection do get :me, action: 'show' end end 

指定操作是可选的。 你可以在这里跳过动作并将控制器动作命名为me

您可以使用

 resources :users, only: [:index, :update] do get :me, on: :collection end 

要么

 resources :users, only: [:index, :update] do collection do get :me end end 

“成员路由将需要一个ID,因为它作用于一个成员。一个收集路径不会因为它作用于一组对象。预览是成员路由的一个例子,因为它作用于(并显示)一个搜索是一个收集路由的一个例子,因为它作用于(并显示)一组对象。“ (从这里 )

当您创建嵌套在资源中的路径时,您可以提及它是成员操作还是集合操作。

 namespace :api, defaults: { format: 'json' } do scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do resources :tokens, :only => [:create, :destroy] resources :users, :only => [:index, :update] do # I tried this match 'me', :via => :get, :collection => true ... ... 

这比Arjan的结果更简单

get 'users/me', to: 'users#me'