# From JumpstartRails AccountMiddleware

class AccountMiddleware
  def initialize(app)
    @app = app
  end

  # http://example.com/12345/projects
  def call(env)
    request = ActionDispatch::Request.new env
    # Fetch the account id from the path
    _, account_id, request_path = request.path.split("/", 3)

    # Check if the id is a number
    if /\d+/.match?(account_id)
      # See if that account is present in the database.
      if (account = Account.find_by(id: account_id))
        # If the account is present, set the Current.account to that
        Current.account = account
      else
        # If not, redirect to the root path
        return [302, {"Location" => "/"}, []]
      end

      request.script_name = "/#{account_id}"
      request.path_info = "/#{request_path}"
    end

    @app.call(request.env)
  end
end
```

## Update the custom tools routes

By default, when generating custom tools, we're adding them to the parent app's routes. Because we're declaring them there, the link helpers don't hold the account id in the params.

```ruby{2-4}
Rails.application.routes.draw do
  scope :avo do
    get "custom_page", to: "avo/tools#custom_page"
  end

  devise_for :users

  # Your routes

  authenticate :user, -> user { user.admin? } do
    mount_avo
  end
end
```

To fix that, we need to move them as if they were added to Avo's routes.

```ruby{13-18}