title: How to save a nested resource in ActiveRecord using a single form (Ruby on Rails 5)
body: <p>I have two entities with a many-to-one relationship. User has many Addresses. When creating a User I want the form to also create a single Address. The entities are nested.</p>
  <p><strong>Approach 1:</strong>
  The code below works, but only saves the User, no associated Address.</p>
  <p>Reading around, I thought that the <code>accepts_nested_attributes_for</code> would automatically save the address. I'm not sure, but it may be that this isn't working because the parameters I'm getting into the Controller don't actually appear to be nested, ie. they look like:</p>
  <pre><code>&quot;user&quot;=&gt;{&quot;name&quot;=&gt;&quot;test&quot;}, &quot;address&quot;=&gt;{&quot;address&quot;=&gt;&quot;test&quot;}
  </code></pre>
  <p>Rather than being nested like this:</p>
  <pre><code>&quot;user&quot;=&gt;{&quot;name&quot;=&gt;&quot;test&quot;, &quot;address&quot;=&gt;{&quot;address&quot;=&gt;&quot;test&quot;} }
  </code></pre>
  <p>I assume this could be due to something wrong in my form, but I don't know what the problem is...</p>
  <p><strong>Approach 2:</strong>
  I have also tried changing the controller - implementing a second private method, <code>address_params</code>, which looked like <code>params.require(:address).permit(:address)</code>, and then explicitly creating the address with <code>@user.address.build(address_params)</code> in the <code>create</code> method.</p>
  <p>When tracing through this approach with a debugger the Address entity did indeed get created successfully, however the <code>respond_to do</code> raised an ArgumentError for reasons I don't understand (&quot;respond_to takes either types or a block, never both&quot;), and this rolls everything back before hitting the save method...</p>
  <p>[EDIT] - The <code>respond_to do</code> raising an error was a red herring - I was misinterpreting the debugger. However, the transaction is rolled back for reasons I don't understand.</p>
  <p><strong>Questions:</strong></p>
  <ol>
  <li>Is one or the other approach more standard for Rails? (or maybe neither are and I'm fundamentally misunderstanding something)</li>
  <li>What am I doing wrong in either / both of these approaches, and how to fix them so both User and Address are saved?</li>
  </ol>
  <p><strong>Relevant code below</strong> (which implements Approach 1 above, and generates the non-nested params as noted):</p>
  <p><strong>user.rb</strong></p>
  <pre><code>class User &lt; ApplicationRecord
    has_many :address
    accepts_nested_attributes_for :address
  end
  </code></pre>
  <p><strong>address.rb</strong></p>
  <pre><code>class Address &lt; ApplicationRecord
    belongs_to :user
  end
  </code></pre>
  <p><strong>users_controller.rb</strong></p>
  <pre><code>class UsersController &lt; ApplicationController
    # GET /users/new
    def new
      @user = User.new
    end
  
    # POST /users
    # POST /users.json
    def create
      @user = User.new(user_params)
  
      respond_to do |format|
        if @user.save
          format.html { redirect_to @user, notice: 'User was successfully created.' }
          format.json { render :show, status: :created, location: @user}
        else
          format.html { render :new }
          format.json { render json: @user.errors, status: :unprocessable_entity }
        end
      end
    end
  
    private
      def user_params
        params.require(:user).permit(:name, address_attributes: [:address])
      end
  
  end
  </code></pre>
  <p><strong>_form.html.erb</strong></p>
  <pre><code>&lt;%= form_for(user) do |f| %&gt;
    &lt;div class=&quot;field&quot;&gt;
      &lt;%= f.label :name %&gt;
      &lt;%= f.text_field :name %&gt;
    &lt;/div&gt;
  
    &lt;%= fields_for(user.address.build) do |u| %&gt;
      &lt;div class=&quot;field&quot;&gt;
        &lt;%= u.label :address %&gt;
        &lt;%= u.text_field :address %&gt;
      &lt;/div&gt;
    &lt;% end %&gt;
  
    &lt;div class=&quot;actions&quot;&gt;
      &lt;%= f.submit %&gt;
    &lt;/div&gt;
  &lt;% end %&gt;
  </code></pre>
  <p><strong>UPDATE 1:</strong></p>
  <p>After making the changes suggested by @Ren, I can see that the parameters look more like what I would've expected for nested resources:</p>
  <pre><code>&quot;user&quot;=&gt;{&quot;name&quot;=&gt;&quot;test&quot;, &quot;addresses_attributes&quot;=&gt;{&quot;0&quot;=&gt;{&quot;address&quot;=&gt;&quot;test&quot;}}}
  </code></pre>
  <p>However, when trying to save the user, the transaction is still rolled back for reasons I don't understand. The output I get from the users.new page is:</p>
  <blockquote>
  <p>2 error prohibited this user from being saved:</p>
  <p>Addresses user must exist</p>
  <p>Addresses user can't be blank</p>
  </blockquote>
  <p>However, using byebug, after the <code>@user = User.new(user_params)</code> call, things look as I would expect them:</p>
  <pre><code>(byebug) @user
  #&lt;User id: nil, name: &quot;test&quot;, created_at: nil, updated_at: nil&gt;
  (byebug) @user.addresses
  #&lt;ActiveRecord::Associations::CollectionProxy [#&lt;Address id: nil, user_id: nil, address: &quot;test&quot;, created_at: nil, updated_at: nil&gt;]&gt;
  </code></pre>
  <p>Obviously the user.id field is not set until the record is written to the DB, so equally the address.user_id field cannot be set until user is saved, so maybe this is caused by some sort of incorrect ordering when ActiveRecord is saving to the database? I will continue to try to understand what's going on by debugging with byebug...</p>
  <p><strong>UPDATE 2:</strong></p>
  <p>Using <code>rails console</code> to test, saving User first and then adding the Address works (both records get written to the DB, although obviously in 2 separate transactions):</p>
  <pre><code>&gt; user = User.new(name: &quot;consoleTest&quot;)
  &gt; user.save
  &gt; user.addresses.build(address: &quot;consoleTest&quot;)
  &gt; user.save
  </code></pre>
  <p>Saving only once at the end results in the same issues I'm seeing when running my program, ie. the transaction is rolled back for some reason:</p>
  <pre><code>&gt; user = User.new(name: &quot;consoleTest&quot;)
  &gt; user.addresses.build(address: &quot;consoleTest&quot;)
  &gt; user.save
  </code></pre>
  <p>As far as I can tell from debugging with <code>rails console</code>, the only difference between the state of <code>user.addresses</code> in these two approaches is that in the first <code>address.user_id</code> is already set, since the <code>user.id</code> is already known, while as in the second, it is not. So this may be the problem, but from what I understand, the <code>save</code> method should ensure entities are saved in the correct order such that this is not a problem. Ideally it would be nice to be able to see which entities <code>save</code> is trying to write to the DB and in which order, but debugging this with byebug takes me down an ActiveRecord rabbit-hold I don't understand at all!</p>