title: Building associations from a form input with array of associated model id's
body: <p>I have the models Game, Player and Country. I'm working on a form with nested fields for <code>Player</code> which should create the Player with it's associated Countries.</p>
  <p>The array of <code>country_ids</code> are sent through a <code>nested_player.hidden_field :country_ids</code> as an array of values.</p>
  <p>game:</p>
  <pre><code>class Game &lt; ApplicationRecord
    has_and_belongs_to_many :players
    accepts_nested_attributes_for :players
  end
  </code></pre>
  <p>player:</p>
  <pre><code>class Player &lt; ApplicationRecord
    has_and_belongs_to_many :games
    has_many :countries
  end
  </code></pre>
  <p>country:</p>
  <pre><code>class Country &lt; ApplicationRecord
    belongs_to :player, optional: true
  end
  </code></pre>
  <p>game controller:</p>
  <pre><code>  def game_params
      params.require(:game).permit(:metadata, players_attributes: [:name, :color, country_ids: []])
    end
  </code></pre>
  <p>form:</p>
  <pre><code>&lt;%= simple_form_for @game do |f| %&gt;
  
    &lt;%= f.fields_for :players do |player| %&gt;
      &lt;%= player.input :name %&gt;
      &lt;%= player.input :color, as: :color %&gt;
      &lt;%= player.hidden_field :country_ids, value: [&quot;226&quot;] %&gt;
    &lt;% end %&gt;
  
    &lt;%= f.submit &quot;Submit&quot;, class: &quot;btn btn-primary&quot; %&gt;
  &lt;% end %&gt;
  </code></pre>
  <p><strong>Problem:</strong></p>
  <p>The controller is receiving the <code>country_ids</code> as expected. The Game and nested <code>Player</code>s are saved, but no player-country associations are built.</p>
  <p>Parameters:</p>
  <pre><code>{&quot;game&quot;=&gt;{&quot;players_attributes&quot;=&gt;{&quot;0&quot;=&gt;{&quot;name&quot;=&gt;&quot;foo&quot;, &quot;color&quot;=&gt;&quot;#000000&quot;, &quot;country_ids&quot;=&gt;&quot;226&quot;}}},
   &quot;commit&quot;=&gt;&quot;Submit&quot;}
  </code></pre>