title: Validate presence of nested attributes within a form
body: <p>I have the following associations:</p>
  
  <pre><code>#models/contact.rb
  class Contact &lt; ActiveRecord::Base
    has_many :contacts_teams
    has_many :teams, through: :contacts
  
    accepts_nested_attributes_for :contacts_teams, allow_destroy: true
  end
  
  #models/contacts_team.rb
  class ContactsTeam &lt; ActiveRecord::Base
    belongs_to :contact
    belongs_to :team
  end
  
  #models/team.rb
  class Team &lt; ActiveRecord::Base
    has_many :contacts_team
    has_many :contacts, through: :contacts_teams
  end
  </code></pre>
  
  <p><strong>A <code>contact</code> should always have at least one associated team (which is specified in the rich join table of <code>contacts_teams</code>).</strong>  </p>
  
  <p>If the user tried to create a contact without an associated team: a validation should be thrown.  If the user tries to remove all of a contact's associated teams: a validation should be thrown.</p>
  
  <p>How do I do that?</p>
  
  <p>I did look at the <a href="http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html" rel="nofollow">nested attributes</a> docs.  I also looked at <a href="http://michaelwelburn.com/2014/02/10/rails-4-nested-object-creation-and-parent-presence-validation-error/" rel="nofollow">this article</a> and <a href="http://homeonrails.com/2012/10/validating-nested-associations-in-rails/" rel="nofollow">this article</a> which are both a bit dated.</p>
  
  <p>For completion: I am using the <code>nested_form_fields</code> gem to dynamically add new associated teams to a contact.  Here is the relevant part on the form (which works, but currently not validating that at least one team was associated to the contact):</p>
  
  <pre><code>&lt;%= f.nested_fields_for :contacts_teams do |ff| %&gt;
    &lt;%= ff.remove_nested_fields_link %&gt;
    &lt;%= ff.label :team_id %&gt;
    &lt;%= ff.collection_select(:team_id, Team.all, :id, :name) %&gt;
  &lt;% end %&gt;
  &lt;br&gt;
  &lt;div&gt;&lt;%= f.add_nested_fields_link :contacts_teams, "Add Team"%&gt;&lt;/div&gt;
  </code></pre>
  
  <p>So when "Add Team" is not clicked then nothing gets passed through the params related to teams, so no <code>contacts_team</code> record gets created.  But when "Add Team" is clicked and a team is selected and form submitted, something like this gets passed through the params:</p>
  
  <pre><code>"contacts_teams_attributes"=&gt;{"0"=&gt;{"team_id"=&gt;"1"}}
  </code></pre>