Alaa Othman
Alaa Othman

Reputation: 1149

Rails passing parent id

I have a UserStory model and a Task model and i want to let users add task to the user story dynamically what i'm about is passing the user story id to the tasks create action could anybody help me please?

user_stories/show

<%= link_to "Add new task",{:controller => ':tasks', :action => :new},:user_story_id: = >@user_story.id, remote: true %>

tasks/new.js.erb

$('#new_task_link').hide().after('<%= j render :partial => "form" %>');

and the tasks/_form

<%= f.hidden_field :user_story_id, :value => params[:user_story_id] %>

Upvotes: 0

Views: 695

Answers (1)

Jay Mitchell
Jay Mitchell

Reputation: 1240

Nest your tasks resources under your user_stories resources in config/routes.rb:

resources :user_stories do
  resources: tasks
end

Your link then becomes:

<%= link_to "Add new task", user_story_tasks_path(@user_story.id) %>

In the TasksController, you'll now have access to :user_story_id in the params.

A Rails Cast covers this. It's a bit outdated (map is no longer necessary in config/routes.rb), but the fundamental concept is still the same.

Upvotes: 3

Related Questions