Rails路由:GET没有param:id

时间:2013-06-12 13:19:59

标签: ruby-on-rails ruby ruby-on-rails-3.2 routes

我正在开发基于rails的REST api。要使用这个API,你必须登录。关于这一点,我想在我的用户控制器中创建一个方法me,它将返回登录用户信息的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作为参数传递。

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

有人有想法吗? 谢谢

7 个答案:

答案 0 :(得分:81)

要走的路是使用singular resources

所以,而不是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"}

答案 1 :(得分:17)

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

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

将它放在resources :users块之外

答案 2 :(得分:10)

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

get 'me', on: :collection

答案 3 :(得分:7)

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

指定操作是可选的。您可以在此处跳过操作并将控制器操作命名为me

答案 4 :(得分:6)

您可以使用

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

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

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

答案 5 :(得分:2)

这比Arjan的结果更简单

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

答案 6 :(得分:0)

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

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
...
...
相关问题