2

I'm having a hard time conceptualizing the best way to set up the resources for this project.

Here are my current routes:

resources :customers do
  resources :jobs
end

resources :jobs
  resources :rooms
  resources :memos
  resources :appliances
  resources :accessories
end

I took my structure from this question: Rails 3 routing: Avoiding Deep Nesting

My question(s) are as follows:

  1. Am I doing this right?
  2. If yes, what does this accomplish that nesting more than 1 level deep does not? I'm assuming it's just absolute paths for things like jobs/rooms/id, instead of customers/jobs/rooms/id - but I don't know if this is correct.

Any further education will be appreciated. Thanks!

Community
  • 1
  • 1
Dustin James
  • 575
  • 9
  • 21

1 Answers1

3
  1. Yes, you are doing it right. You could either nest the resources or not, it is up to you.

  2. Nesting one more level usually "forces" you to find each resource.

Consider these routes:

resources :customers do
  resources :jobs do
    resources :rooms
  end
end

Then you would have relative paths like /customers/1/jobs/2/rooms/3/show.This implies that the Room #3 belongs to Job #2 which belong to Customer #1.

In other words, you would end up for the show action of the RoomsController with 3 instances: @customer, @job and @room, all set by a SQL query.

But you already defined that a room belongs to a job and that a job belong to a room. So do you really have to run 3 SQL queries? No, which is why you avoid deeply nested routes (over 2~3 levels).

MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
  • Perfect - that makes a lot more sense when it's explained in terms of SQL queries! – Dustin James Aug 08 '14 at 19:45
  • @MrYoshi could you take a look at this issue? It's almost the same, but I can't figure it out. http://stackoverflow.com/questions/35672666/rails-structuring-routes-controller-views-for-nested-resources – Sean Magyar Feb 27 '16 at 17:04