Reputation: 51
How might I be able to shorten these extremely lengthy routes in my rails application?
# routes.rb
resources :courses do
resources :sections do
resources :lessons do
resources :sub_lessons
end
end
end
Upvotes: 0
Views: 206
Reputation: 648
I recommend to follow the rails oficial guides. It is considered a good practice to avoid nesting resources more than 1 level deep. That said, if you really need this level of nesting you can use the shallow
option. this way at least your routes will be cleaner. As noted in the documentation cited above:
One way to avoid deep nesting (as recommended above) is to generate the collection actions scoped under the parent, so as to get a sense of the hierarchy, but to not nest the member actions. In other words, to only build routes with the minimal amount of information to uniquely identify the resource
You could try something like this:
resources :courses, shallow: true do
resources :sections, shallow: true do
resources :lessons, shallow: true do
resources :sub_lessons
end
end
end
Just play around with this a little and use rake routes
to see how your routes are looking like.
However, what you should ask yourself is, for example do I need to have lessons routed under sections? May be its better to split them, something like:
resources :courses do
resources :sections
end
resources :lessons do
resources :sub_lessons
end
It all depends on the scope you need in what action, for example if at certain action you need to limit lessons based on courses but not in sections, then you will only need the course id passed as a parameter.
Upvotes: 1