title: Validation on a has_many relationship in rails 3.2
body: <p>Given that I have the next models:</p>
  
  <p>user.rb</p>
  
  <pre><code>has_many :favorites, dependent: :destroy
  has_many :sports, through: :favorites
  </code></pre>
  
  <p>sport.rb</p>
  
  <pre><code>has_many :favorites, dependent: :destroy
  has_many :users, through: :favorites
  </code></pre>
  
  <p>In the form for create a new user, there is a list of checkboxes of sports, and in the user validation I want to validate that at least one is selected. </p>
  
  <p>I'm doing it like this:</p>
  
  <p>In the user controller create action:</p>
  
  <pre><code>@user = User.new(params[:user])
  @user.sports &lt;&lt; Sport.find(params[:sports]) unless params[:sports].nil?
  
  if @user.save ...
  </code></pre>
  
  <p>In the user model</p>
  
  <pre><code>validate :user_must_select_sport
  
  def user_must_select_sport
    if sports.empty?
      errors.add(:Sport, "You have to select at least 1 sport")
    end
  end
  </code></pre>
  
  <p>And it's actually working, but I'm guessing that it has to be a better way of doing this. I'd appreciate any help.</p>