Rails routes: GET without param :id

后端 未结 7 980
名媛妹妹
名媛妹妹 2021-01-01 08:56

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 wi

相关标签:
7条回答
  • 2021-01-01 09:10

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

    get 'me', on: :collection
    
    0 讨论(0)
  • 2021-01-01 09:14

    This gives same result as Arjan's in simpler way

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

    0 讨论(0)
  • 2021-01-01 09:17

    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
    ...
    ...
    
    0 讨论(0)
  • 2021-01-01 09:20

    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)

    0 讨论(0)
  • 2021-01-01 09:26

    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

    0 讨论(0)
  • 2021-01-01 09:30
      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.

    0 讨论(0)
提交回复
热议问题