Rails Nested Resources - 09 Mar 2012

Here’s a quick run down on using nested resources in your Ruby on Rails applications. To get started, you’ll need to add the resources to your routes.rb file. For this example we’re going to look at lists and tasks.

resources :lists do
  resources :tasks

That will set you up with the following routes and more:


new_list_task_path( @list )
list_task_path( @list, @task )

Nested routes are a great way to clean up URLs, as well as provide parameters for your controllers. If we use new_list_task_path( @list ), we can do the following in our controller:

before_filter :list, on: [ :new ]

def new
  @task =

def list
  @list = current_user.lists.find_by_id( params[:list_id] )
  redirect_to new_user_url if @list.nil?

Our new routes are passing the :list_id to our controller, which allows us to authenticate the current_user and build the new task quickly and easily.