问题描述
我正在开发基于Rails的REST api。要使用此api,您必须先登录。关于这一点,我想在我的用户控制器中创建方法 me
,该方法将返回已登录用户的json。资讯
因此,我不需要:id
在URL中传递。我只想致电
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...
有人知道吗?
谢谢
Anyone has an idea?Thank you
推荐答案
资源路由被设计为以这种方式工作。如果您想要与众不同,则可以自己设计,就像这样。
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
将其放在您的资源之外:用户
阻止
这篇关于Rails路线:不带参数的GET:id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!