Search code examples
ruby-on-railsrails-routing

Static nested resource params name on Rails routes


I'm playing on Rails routing but I can't figure out how to manage this. The problem is at user_posts(1) and user(4) routes, the params have different names - id and user_id

What I'm trying to achieve is a static param name for the same resource.

I have this route file

Rails.application.routes.draw do
  shallow do
    resources :users, module: :users, only: [:index, :show] do
      resources :posts, module: :posts, only: [:index, :show]
    end
  end
end

The routes generated are

   user_posts(1) GET  /users/:user_id/posts(.:format)      users/posts/posts#index
   post(2) GET        /posts/:id(.:format)                 users/posts/posts#show
   users(3) GET       /users(.:format)                     users/users#index
   user(4) GET        /users/:id(.:format)                 users/users#show

I tried resources :user param: :user but the generated route at user_posts is /users/:user_user_id/posts

Is possible to achieve a :user_id param and :post_id param for every route using resources?


Solution

  • Try this

    resources :users, param: :user_id
    resources :users, only: [] do
        resources :posts, param: :post_id
    end