title: How to set and unset build_association depending on contents of a text_field in Rails?
body: <p>I have a simple Rails form that uses a conditional build_association (if there's not already an associated parent) to include a text_field to edit a parent. This is useful if a new record for the parent should be added. The problem with this is that if a parent already exists, if the text_field is updated then it will be changed for the parent record affecting many children. If build_association is called regardless of whether a parent association already exists, then new, duplicate parents will constantly be created. </p>
  
  <p>I am trying to understand how I can use build_association and fields_for to add a new parent to the database if the user types in an unfamiliar name, but to set the parent to be an existing record if the name matches an existing parent's name. (If I can get this part to work right, the next step will be to add autocomplete.) The code is below:</p>
  
  <pre><code>    &lt;%= form_for @sermon, :html =&gt; { :multipart =&gt; true } do |f| %&gt;
        &lt;div class="field"&gt;
          &lt;%= f.label :title %&gt;&lt;br /&gt;
          &lt;%= f.text_field :title %&gt;
        &lt;/div&gt;
        &lt;div class="field"&gt;
          &lt;%= f.label :date %&gt;&lt;br /&gt;
          &lt;%= f.text_field :date %&gt;
        &lt;/div&gt;
  &lt;div&gt;
      &lt;% @sermon.build_speaker unless @sermon.speaker %&gt;
          &lt;%= f.fields_for :speaker do |g| %&gt;
              &lt;%= g.label :name, "Speaker name:" %&gt;&lt;br /&gt;
              &lt;%= g.text_field :name %&gt;
              &lt;%= g.submit %&gt;
          &lt;% end %&gt;
      &lt;/div&gt;
        &lt;div class="actions"&gt;
          &lt;%= f.submit %&gt;
        &lt;/div&gt;
      &lt;% end %&gt;
  </code></pre>