Search code examples
ruby-on-railsruby-on-rails-4rails-routingnested-resources

Adding a namespace within a resource in rails


I'm trying to figure out how to do some routing in a Rails 4 app. This is my first question, so I'll do my best.

I have accounts. A user can belong to multiple accounts. An account can have multiple "modules" enabled -- buyer / seller.

resources :accounts do
  member do
    namespace :seller do
      resources :contracts do
        get "history", on: :member
      end
    end
    namespace :buyer do
      resources :contracts do
        get "history", on: :member
      end
    end
  end
end

Ideally, the accounts, and contracts (in each namespace) would remain resourceful.

The problem is that when you see the routes that are created, the nested contract resource, and the account are both using :id in the params

stuff_buyer_contract GET /accounts/:id/buyer/contracts/:id/stuff(.:format)

I assume I'll get a bunch of "shallow routes" answers, but is there anyway to do it as is, where the :id params will be correct?

I would like the routing to look like:

stuff_buyer_contract GET /accounts/:account_id/buyer/contracts/:id/stuff(.:format)


Solution

  • Try the below route configuration:

      resources :accounts do
          namespace :seller do
            resources :contracts do
              get "history", on: :member
            end
          end
          namespace :buyer do
            resources :contracts do
              get "history", on: :member
            end
          end
      end