Tuesday, November 23, 2010

Ruby on Rails: Using Multiple Subdirectories in Views

Hello,

I was working on a rails project when I realized that I wanted to use multiple subdirectories in views for the same controller, in order to clarify inside the url where we were navigating.

For example, for a controller vehicles, I could want to make three subcategories (trucks, vans and cars), and inside each subcategory, i could add more views (cars -> latest, cars -> old, cars -> red, ...)

For that purpose I wanted to have a view directory structure like this:

trucks
  - new
  - old
  - red
vans
  - new
  - old
  - red
cars
  - new
  - old
  - red

In order to accomplish this in an easy way (not modifying the routes.rb nor anything similar), the easy way is to use the following code in your vehicles controller:

def cars
    render :action =>
"cars/index"
end

This way, you can call all the actions you want, organize them in any subdirectory structure, and keep your code clean.