title: Rails 5 - how to dynamically add to the form a nested object using autocomplete
body: <p>I have 3 models - team, user and team_user (has_namy: through). In the form of edit and new team to do the ability to dynamically add members of this team with autocomplete input.</p>
  
  <p>app/models/user.rb</p>
  
  <pre><code>class User &lt; ApplicationRecord
    has_many :team_users
    has_many :teams, through: :team_users
    accepts_nested_attributes_for :team_users, :teams, allow_destroy: true
  end
  </code></pre>
  
  <p>app/models/team.rb</p>
  
  <pre><code>class Team &lt; ApplicationRecord
    has_many :team_users
    has_many :users, through: :team_users
    accepts_nested_attributes_for :team_users, allow_destroy: true, reject_if: proc { |a| a['user_id'].blank? }
  end
  </code></pre>
  
  <p>app/models/team_user.rb</p>
  
  <pre><code>class TeamUser &lt; ApplicationRecord
    belongs_to :team
    belongs_to :user
    accepts_nested_attributes_for :team, :user, allow_destroy: true
  end
  </code></pre>
  
  <p>I need something like this:</p>
  
  <p><a href="https://i.stack.imgur.com/hUoi3.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hUoi3.gif" alt="enter image description here"></a></p>
  
  <p>The problems that I have:</p>
  
  <ul>
  <li>Cocoon Gem generate only empty fields or that I will create when the template is rendered. And I need to find a user and add him to the team (in a non-editable field)</li>
  <li>If I use AJAX, the <code>@team = Team.new</code> runs only in a new action in <code>TeamsController</code> and Rails doesn't remember created <code>@team</code>, when AJAX is trying to create <code>team_user</code> object. To create a object of <code>team_user</code> model need to run <code>@team.team_users.build(user_id: params[:user_id])</code>. The <code>user_id</code> I get from autocomplete field, but don't know <code>@team</code> and <code>team_id</code> (for example, in <code>new</code> action <code>TeamsController</code>).</li>
  </ul>