title: Rails form_for Error | How to Bind Nested ActiveRecord Object to Form
body: <p>I was developing a Ruby on Rails application. It has a nested route like so:</p>
  
  <pre><code>Rails.application.routes.draw do
    root 'trip_plans#index'
    resources :trip_plans do
      resources :places, except: [:show, :index]
    end
  end
  </code></pre>
  
  <p>The <code>trip_plans</code> resource has a <code>TripPlan</code> model and the <code>places</code> resource has a <code>Place</code> model. According to the routes, the <code>new_trip_plan_place_path</code> is a route like <code>/trip_plans/:trip_plan_id/places/new</code>. The <code>views/places/new.html.haml</code> uses a <code>form_for</code> declaration to create a new place within the current <code>trip_plan</code>:</p>
  
  <pre><code>- content_for :title do
    %title Add a Place to Your Plan
  
  %header.form-header
    .container.form-container
      .row
        .col-xs-12
          %h1 Add a Place
          %hr
  
  %article
    %section
      .container.form-container
        = render 'form'
  </code></pre>
  
  <p>The corresponding <code>edit.html.haml</code> is essentially the same, calling the same <code>_form.html.haml</code> to render the form.</p>
  
  <p>The <code>places_controller</code>'s both <code>new</code> and <code>edit</code> action is like:</p>
  
  <pre><code>def new
    @trip_plan = TripPlan.find(params[:trip_plan_id])
    @place = @trip_plan.places.build
  end
  
  def edit
    @trip_plan = TripPlan.find(params[:trip_plan_id])
    @place = @trip_plan.places.build
  end
  </code></pre>
  
  <p>And the <code>_form.html.haml</code> uses the <code>@place</code> like so:</p>
  
  <pre><code>= form_for @place do |f|
  </code></pre>
  
  <p>But as <code>@place</code> is a dependent ActiveRecord object, Rails is not able to figure out the correct URLs for <code>new</code> and <code>edit</code> path. It always shows a new form even on <code>edit</code> page.</p>
  
  <p>How can I fix this?</p>
  
  <p>Thanks in advance!</p>