Topic: Associations, create a task for a project from project index view


Let say, i have an association between a project and a task.
A project has_many taks and a task belongs_to a project.
My model is working great.
I can create tasks from project and so on but my problem comes when i
want to add a button on the project index view to add task to a

What i want is something like that
(project index view)

Project 1 Show, edit, destroy, add_task
Project 2 Show, edit, destroy, add_task

So that when i click add_task of project1 I’m redirected to a new task
form to create a task for that project.

I’ve added <%= link_to 'add_task', new_task_path(:project_id =>
project) %> in the project index view

so when i click on add_task, it redirects me to /task/new?project_id=1

but when i submit the task, the task is not linked to the project.
How can i get the project_id?

Does anyone has a tutorial or an example of how should I do?


Re: Associations, create a task for a project from project index view

If you admit that a tsk can only be created in the context of a project, you should adapt your routes:

resources :projects do
  resources :tasks

To display the available routes run 'rake routes' in your terminal. In your case to add a new task to a project, the link should like like that:

<%= link_to "Ad task", project_task_path(@project, @task) %>

Don't forget to find the corresponding project in the tasks controller before creating a new task (in 'before_filter' action, for example).
See more details on nested routes at Rails guides: … -resources