Ben
Ben

Reputation: 33

Passing a parameter to a 'new' action via link_to

Rails newbie here and I'm stumped. In Rails I have a Project Model which has_many Tasks. Lets say I have a view that is displaying 5 projects and each project has a 'New Task' link so that the user can add a new task to any one of the projects. So:

Project 1
New Task

Project 2
New Task etc.

If the New Task link looks like

link_to 'New Task', new_task_path

what is the best way to tell the 'new' action on the tasks controller which link was clicked? I figure I have to pass the project_id to the new task, but I can't solve out how to do it.

Help appreciated as always!

Upvotes: 2

Views: 2903

Answers (1)

ctide
ctide

Reputation: 5257

Depends how your routes are defined, but if tasks are defined as a subresource of a project (such as the following) then it's pretty simple.

resources :projects do
  resources :tasks
end

This will generate routes such as:

new_project_task GET    /projects/:project_id/tasks/new(.:format)                         {:controller=>"tasks", :action=>"new"}

And then you can link to it via:

link_to 'New Task', new_project_task_path(@project)

Upvotes: 7

Related Questions