Tests

Finding What the Convention Is

The first thing I wanted to know, was how rails took care of this. In other words I wanted to know the convention, yes the code snipped I linked before was from the rails routes, but it has a lot of noise and other elements, and I want something easier to analyze.

So I decided to just create a new project, and see what bin/rails g scaffold category/Product name did. Here it is:

namespace :category do
    resources :products
end
resources :categories

Then I ran bin/rails routes to see what it looked like. I will give you a summary.

Basically:

Okay. So this is what we want ideally. I could be happy with this, but I wanna know what namespace actually changes, so lets run another test.

Nesting resources

Lets try this out:

resources :categories do
    resources :products
end

After running bin/rails routes there are a few differences:

The only thing that stayed the same is the prefixes. Which, I honestly have no idea why only they changed. So that further builds into my doubt about this... So I decided to create a new rails test project with rails new tests2 and see what the controllers look like... First I added that snippet back on the routes.

Then I ran the commands to generate the models:

Created the controllers

Migrated. And created some data in the console.

> clothing = Category.create(name: "Clothing")
> clothing.products.create(name: "Tshirt")
> clothing.products.create(name: "Pants")
> clothing.products.create(name: "Socks")

Then I booted up the server, and checked the routes. After this I confirm my suspicions. The Controller#Action path is the path on the controllers folder, and it is completely disconnected from the route. The route has two elements.

If we wanted it to be organized, we would make it the same. (I cannot think of any use for the route to be different from the controller path). Now, how do the views get affected by this?

difference between view directories on the left (old) compared to the right (new)

Well that seems explanatory enough. Nesting resources gives us nested routes, but not nested controllers or views. Why is that? That is part of the question I am asking. But we haven't seen everything yet, lets go to modules and scopes, which I have not tested yet...

Modules and Scopes

Now I wanna try two different things and see how they differ:

scope module: "category" do
    resources :products
end
resources :categories

Here, the differences compared to what we want are:

Even though I gave index as an example, these patterns apply to all the routes

To conclude: Using scope :module gives us nested routes and views, but not routes or prefixes.

resources :categories
resources :products, module: "category"

Finally this one... which does the same thing as scope :module (though I had an idea since it said as an alias in the docs)