title: Teams of users rails app
body: <p>I need to create teams of users. A user belongs to a team (only one team) a team has many users. I can't figure out how to get a user to be able to create, join, and leave a team. Below is what I have so far, but I'm sure I'm doing something terribly (and "newby" wrong).</p>
  
  <p>User Model:</p>
  
  <pre><code>belongs_to :teams, dependent: :destroy
  
  def team_member?(team)
      team_relationships.find_by_team_id(team.id)
  end
  
  def join!(team)
      team_relationships.create!(team_id: team.id)
  end  
  
  def unjoin!(team)
      team_relationships.find_by_team_id(team.id).destroy
  end
  </code></pre>
  
  <p>team model</p>
  
  <pre><code>has_many :users, through: :team_relationships, dependent: :destroy
  
  attr_accessible :team_name, :team_id
  
  validates :user_id, presence: true
  validates :team_name, presence: true, length: { maximum: 140 }
  
  default_scope order: 'teams.created_at DESC'
  </code></pre>
  
  <p>team_relationship model</p>
  
  <pre><code>attr_accessible :team_id
  
  belongs_to :team
  belongs_to :user
  
  validates :team_id, presence: true  
  </code></pre>
  
  <p>routes:</p>
  
  <pre><code>  resources :teams do
      member do
        get 'join'
        get 'leave'
      end
    end
  </code></pre>
  
  <p>teams_controller:</p>
  
  <pre><code>def join
    @team = Team.find params[:team_id]
    current_user.update_attribute(:team_id, @team.id)
    redirect_to @user
  end
  
  def leave
    @team = Team.find params[:id]
    current_user.update_attribute(:team_id, nil)
    redirect_to @user
  end
  </code></pre>
  
  <p>_join_team.html.erb</p>
  
  <pre><code>&lt;%= form_for(current_user.team_relationships.build(team_id: @team_id),
               remote: true) do |f| %&gt;
    &lt;div&gt;&lt;%= f.hidden_field :team_id %&gt;&lt;/div&gt;
    &lt;%= f.submit "Join", class: "btn btn-large btn-primary" %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>_unjoin_team.html.erb</p>
  
  <pre><code>&lt;%= form_for(current_user.team_relationships.find_by_team_id(@team_id),
           html: { method: :delete }) do |f| %&gt;
    &lt;%= f.submit "Leave Team", class: "btn btn-large" %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>If you can't tell I was trying to adapt some of what's in Hartl's tutorial for this purpose. What am I doing wrong?</p>
  
  <p>I believe I have gotten the models figured out, but now I'm not sure how to get a user to create a team, destroy a team, join a team, or leave a team. What do I have to do in the models, controllers, and views to make it happen?</p>