Rails 路由:不带参数的 GET :id [英] Rails routes: GET without param :id

查看:23
本文介绍了Rails 路由:不带参数的 GET :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 块之外

这篇关于Rails 路由:不带参数的 GET :id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆