Goz*_*zup 38 ruby routes ruby-on-rails ruby-on-rails-3.2
我正在开发基于rails的REST api.要使用这个API,你必须登录.关于这一点,我想me在我的用户控制器中创建一个方法,它将返回登录用户信息的json.所以,我不需要:id在URL中传递.我只想打电话给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
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我的路线等待身份证,但我想得到像设计一样的东西.基于current_userid的东西.示例如下:
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
Run Code Online (Sandbox Code Playgroud)
在此示例中,您可以编辑当前用户密码,而无需将id作为参数传递.
我可以使用集合而不是成员,但这是一个肮脏的旁路......
有人有想法吗?谢谢
Wai*_*... 92
要走的路是使用奇异的资源:
所以,而不是resources使用resource:
有时,您拥有一个客户端始终查找而不引用ID的资源.例如,您希望/ 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"}
Run Code Online (Sandbox Code Playgroud)
Arj*_*jan 18
资源路由旨在以这种方式工作.如果你想要不同的东西,可以自己设计,就像这样.
match 'users/me' => 'users#me', :via => :get
Run Code Online (Sandbox Code Playgroud)
把它放在你的resources :users街区之外
您可以使用
resources :users, only: [:index, :update] do
get :me, on: :collection
end
Run Code Online (Sandbox Code Playgroud)
要么
resources :users, only: [:index, :update] do
collection do
get :me
end
end
Run Code Online (Sandbox Code Playgroud)
"A构件的途径将需要的ID,因为它作用在构件上.集合路线不会因为它作用于对象的集合.预览是一个构件路径的一个例子,因为它作用于(和显示器)单搜索是一个收集路由的一个例子,因为它作用于(并显示)一组对象." (从这里)
小智 7
resources :users, only: [:index, :update] do
collection do
get :me, action: 'show'
end
end
Run Code Online (Sandbox Code Playgroud)
指定操作是可选的.您可以在此处跳过操作并将控制器操作命名为me.
| 归档时间: |
|
| 查看次数: |
31648 次 |
| 最近记录: |