Rails 路线:GET 没有参数 :id [英] Rails routes: GET without param :id
问题描述
我正在开发一个基于 rails 的 REST api.要使用此 api,您必须登录.关于这一点,我想在我的用户控制器中创建一个方法 me
,它将返回登录用户信息的 json.所以,我不需要在 URL 中传递 :id
.我只想调用 http://domain.com/api/users/me
I'm developing a REST api based on rails. To use this api, you MUST be logged in. Regarding that, I'd like to create a method me
in my user controller that will return a json of the logged in user infos.
So, I don't need an :id
to be passed in the URL. I just want to call 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
如您所见,我的路线等待一个 id,但我想得到类似 devise 的东西.基于 current_user
id 的东西.示例如下:
As you can see, my route waits for an id, but I'd like to get something like devise has. Something based on current_user
id. Example below:
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
在此示例中,您可以编辑当前用户密码,而无需将 id 作为参数传递.
In this example you can edit the current user password without passing the id as a param.
我可以使用集合而不是成员,但这是一个肮脏的绕过...
I could use a collection instead of a member, but that's a dirty bypass...
有人有想法吗?谢谢
推荐答案
资源路由旨在以这种方式工作.如果您想要不同的东西,请自己设计,就像这样.
Resource routes are designed to work this way. If you want something different, design it yourself, like this.
match 'users/me' => 'users#me', :via => :get
把它放在你的 resources :users
块之外
Put it outside of your resources :users
block
这篇关于Rails 路线:GET 没有参数 :id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!