Rails routes: GET without param :id

五迷三道 提交于 2019-11-30 10:46:18

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

Put it outside of your resources :users block

Waiting for Dev...

The way to go is to use singular resources:

So, instead of resources use resource:

Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like /profile to always show the profile of the currently logged in user. In this case, you can use a singular resource to map /profile (rather than /profile/:id) to the show action [...]

So, in your case:

resource :user do
  get :me, on: :member
end

# => me_api_user GET    /api/users/me(.:format)            api/v1/users#me {:format=>"json"}
EfratBlaier

Maybe I am missing something, but why don't you use:

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

specifying the action is optional. you can skip action here and name your controller action as me.

You can use

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

or

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

"A member route will require an ID, because it acts on a member. A collection route doesn't because it acts on a collection of objects. Preview is an example of a member route, because it acts on (and displays) a single object. Search is an example of a collection route, because it acts on (and displays) a collection of objects." (from here)

This gives same result as Arjan's in simpler way

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

When you create a route nested within a resource, you can mention, whether it is member action or a collection action.

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
...
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!