ruby-on-railsruby-on-rails-4.2

routes with wrong params


I have the following route:

resources :users, only: [] do
  resources :events, only: %i[index]
  delete :close_account, on: :member
end

for some reason, it generate routes with different params:

       GET      /backoffice/users/:user_id/events(.:format)               backoffice/events#index
       DELETE   /backoffice/users/:id/close_account(.:format)             backoffice/users#close_account

in one route, the param is user_id and the route below is id. I wanted both to be user_id, so I added resources :users, param: :user_id

and now the routes are weirder than before:

      GET      /backoffice/users/:user_user_id/events(.:format)          backoffice/events#index
      DELETE   /backoffice/users/:user_id/close_account(.:format)        backoffice/users#close_account

how can I fix this routes in such a way that both routes have the same param?


Solution

  • The parameters are not "wrong". The reason you're seeing this behavior is that the id parameter name is here reserved to the innermost resource. That is, if your EventsController had some other actions besides index, it would receive the event id as id, while the related User id would be user_id. The other route is not a nested resource, and as such has no need for different prefixes.

    This can be seen in the Rails guides section on nested resources.

    That being said, if you truly want both to be referred to as user_id, you should use

    delete "/backoffice/users/:user_id/close_account/", to: "backoffice/users#close_account"