mockra

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
end

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

/lists/:id/tasks
/lists/:id/tasks/new
/lists/:id/tasks/:id

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 = @list.tasks.build
end

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

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.