title: Create a child model in rails (belongs_to) and pre-setting the parent ID
body: <p>I'm sure I'm missing something simple, but not being aware of the right terminology in Rails, I can't find what I'm looking for....</p>
  
  <p>A <code>Project</code> model has_many <code>Task</code>, and a <code>Task</code> belongs_to a <code>Project</code>.</p>
  
  <p>My <code>routes.rb</code> has </p>
  
  <pre><code>resources :projects
  resources :tasks
  </code></pre>
  
  <p>I can create/edit/modify <code>Projects</code> just fine, and I can also edit <code>Tasks</code>... but I can't seem to work out how to create a new <code>Task</code>, assigning the correct <code>Project</code> when doing so.</p>
  
  <p>My <code>Project</code> page (eg. /projects/2) has an Add Task link which goes to /task/new, so I'm losing the connection. I don't want to make a nested resource, because <code>Tasks</code>, once created, will be uniquely identifiable by their ID, and in future has_many other models as well.</p>
  
  <p>Is there a quick fix here?</p>
  
  <p><strong>edit</strong> Well I've managed to solve this.... it's ugly and it's horrible and I'm not sure why it has to be that way, but it works.</p>
  
  <p>My routes:</p>
  
  <pre><code>resources :projects do
    resources :tasks, :only =&gt; [:new]
  end
  
  resources :tasks, :except =&gt; [:new]
  </code></pre>
  
  <p>My task controller:</p>
  
  <pre><code>def new
    @project = Project.find(params[:project_id])
    @task = @project.tasks.build
  end
  
  # Process the form for creating a new task.
  def create
    @project = Project.find(params[:task][:project_id])
    @task = @project.tasks.build(params[:task])
    if @task.save
      flash[:success] = 'Task created.'
      redirect_to project_path(@project)
    else
      render 'new'
    end
  end
  </code></pre>
  
  <p>And my Task form:</p>
  
  <pre><code>&lt;%= semantic_form_for @task do |f| %&gt;
  
  &lt;%= render 'shared/form_message', :object =&gt; f.object %&gt;
  
  &lt;%= f.inputs do %&gt;
      &lt;%= f.input :name %&gt;
      &lt;%= f.input :project %&gt;
  &lt;% end %&gt;
  
  &lt;ul class="formActions"&gt;
      &lt;li class="list"&gt;&lt;%= link_to 'Back to list', project_path(@task.project) %&gt;&lt;/li&gt;
      &lt;li&gt;&lt;%= f.submit "Save" %&gt;&lt;/li&gt;
  &lt;/ul&gt;
  
  &lt;% end %&gt;
  </code></pre>
  
  <p>I didn't want to have to put the project box on the form, and I'm still not sure why I have to, and also why I needed to take :create <em>out</em> of the nested routes. It also seems quite laborous, for such a common task, but it works, so.... I guess it's all good.</p>