Take the 2-minute tour ×

I'm working on a Rails 3 task demo project in which each instance of Project has many tasks, and instances of Task belong to one project. However, this latter relationship is optional, although it's defined in the Task model as belongs_to :project.

Essentially, I want to be able to have routes like the following:



I'm not sure if this is possible or even good practice. Really what's most important is for me to be able to create project-less tasks from within the general tasks#index action, and tasks belonging to a project from within the project#show action via links to new actions.

I've read Rails Routing from the Outside In, but it didn't really explain what I'm going for.

Any help would be greatly appreciated.

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

This is actually more common than you think. Here is a solution:

class TasksController < ApplicationController
before_filter :get_project
before_filter :get_tasks


  def get_project
    @project = Project.find(params[:project_id]) if params[:project_id]

  def get_tasks
    @tasks = (@project) ? @project.tasks : Task


From there you, you would always reference @tasks when you want to get the tasks.

So for an example:

def new

Would yield correct results whether you are nested or not.

In the case of nested, it would be like calling:


and without nested, it would be like calling:

share|improve this answer
you could do: Project.tasks.create(params[:tasks].merge({:project_id=>params[:id]}) where params[:task] is just a hash that you would pass into #create. –  Mike Lewis Apr 11 '11 at 0:46
Got it figured out with your advice, and tied it in with Devise. After setting up the routes, I really didn't have to change much else beyond what I originally had, other than that the new link_to tag is link_to 'New Task', @project ? "#{@project.id}/tasks/new" : new_task_path –  clem Apr 11 '11 at 0:53
awesome, good to hear! –  Mike Lewis Apr 11 '11 at 0:59
add comment

The routes do not relate with associations. You can have any routes you like, even if you do not have any associations. And your routes seem good.

The association is a convenience thing. It makes the programmer's life easier. If you even need to write something like :


Then, you have to have a has_many(or other) association between tasks/projects. This has many is the one that allows you to do task.projects. If you did not have the association, you would have to use a finder.

share|improve this answer
add comment

Your Answer


