I was confused when I first learned about namespaced routes in rails because I had already learned about nested routes and the difference wasn’t immediately apparent, so I want to quickly lay out and look at the differences in the two and also talk about another way to namespace routes — using the scope method.
First let’s talk about the namespaced routes because I think that it is the most simple. Namespaced routes simply prepend the name before the route. For example:
this will result in these routes:
as you can see the routes have all been prepended with admin as well as their named route methods.
Now let’s look at namespace’s brother: scope. Scope is similar to namespace but leaves us with more options. lets look at this example:
Now that were using scope we can tell our routes which controller module to use and what to use as a prefix for out named routes:
Ok so that makes sense… but how are nested routes different?? well lets look!
So this looks simple again… like the namespaced routes without all the extra arguments. But if we look at the return we will see the differences clearly:
As you can see the routes from the nested resources leave us needing an [:admin_id]. This admin ID means that these routes belong to a specific instance of an admin Class. So when we travel to “admin/2/posts” were traveling to the posts that belong to admin number 2.
I hope this helps clear up some of the differences between some types of routes!