title: accepts_nested_attributes_for with validations and using find_or_create_by
body: <p>I have a <code>user</code> model and a <code>town</code> model.  A <code>user</code> belongs_to a <code>town</code>:</p>
  
  <pre><code># models/user.rb
  class User &lt; ApplicationRecord
    belongs_to :town
    accepts_nested_attributes_for :town
    validates :last_name, presence: true
  end
  </code></pre>
  
  <p><br></p>
  
  <pre><code># models/town.rb
  class Town &lt; ApplicationRecord
    has_many :users
    validates :name, presence: true
    validates :name, uniqueness: true
  end
  </code></pre>
  
  <p>You go to create a new <code>user</code> record: there is a text_box in order to put in the associated town's <code>name</code>.  When submitted, the rails application should do the following:</p>
  
  <ul>
  <li>use <code>find_or_create_by</code>. go and check if there already exists a <code>town</code> record with the <code>name</code> attribute passed in.
  
  <ul>
  <li>If a <code>town</code> record DOES exist with that given <code>name</code> attribute, just associate that existing <code>town</code> record to this new <code>user</code> record</li>
  <li>If a <code>town</code> record DOES NOT exist with that given <code>name</code> attribute, then create a new <code>town</code> record with that <code>name</code> attribute, and associate that one to this <code>user</code> record</li>
  </ul></li>
  <li>If any validations fail, do not create a <code>user</code> record or a <code>town</code> record and re-render the form.</li>
  </ul>
  
  <p>I am having real trouble with this.  <a href="https://stackoverflow.com/questions/3579924/accepts-nested-attributes-for-with-find-or-create">This question</a> suggests putting <code>autosave</code> on the <code>belongs_to :town</code> statement, as well as defining a method called <code>autosave_associated_records_for_town</code>.  However: I just could not get that to work.</p>
  
  <p>Appreciate it!</p>