Nested routes and relative paths

Hi there,

Trying to get my head around nested routes for the following example:

I have a site with the following urls:
localhost/region/usa/restaurant
localhost/region/usa/city/new-york/restaurant

So my router.ex looks like:

scope "/", RestaurentWeb do
  pipe_through :browser
  
  # to handle localhost/region/usa/city/nyc/restaurant
  resources "region", RegionController do
    resources "city", CityController do
      resources "restaurant", RestaurantController do
        post "/book", BookingController, :book_table
      end
    end
  end

  # to handle localhost/region/usa/restaurant
  resources "region", RegionController do
    resources "restaurant", RestaurantController do
      post "/book", BookingController, :book_table
    end
  end

end

Let’s say I get down to region/city, and I have a standard HTML template for :show action of Restaurant with a link to book a table which takes me to, say, restaurant/1234-restaurant-name/book, so in the show.html.eex template there is a link that looks like

<%= link "Book table", to: Routes.region_city_restaurant_book_path(..) %>

Now, I would like to render the same show template when I am under /region for the same restaurant, but in this case I would need to have a link with to: Routes.region_restaurant_path(..)

Is there a way to use Routes and set it up to go to /book so the link to-path can change dynamically from “where I am” in the url?

Is seems I cannot do this as all Routes.path begin with “/” and is scoped from the root (i.e. localhost in this case), so is my only option to parse and do string splitting on the path?

Thanks.

I’m not really sure what you are asking for the route helpers, but you could always pass the route into the template from another template, or pass in bindings to let it build it up, etc… :slight_smile:

Also, as an aside, it’s generally more common to keep root forms together, so instead the above example would be:

scope "/", RestaurentWeb do
  pipe_through :browser
  
  # to handle localhost/region/usa/city/nyc/restaurant
  resources "region", RegionController do
    resources "city", CityController do
      resources "restaurant", RestaurantController do
        post "/book", BookingController, :book_table
      end
    end

    resources "restaurant", RestaurantController do
      post "/book", BookingController, :book_table
    end
  end

end
1 Like

Thanks, I was thinking if the Routes macro are being run from partial templates, they can be rendered in different depths but produce the same links, but can see this is not possible.