Passing a parameter to a 'new' action via link_to
Rails 开发者_如何学Cnewbie 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 TaskProject 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!
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)
精彩评论