2012-08-27 157 views
-1

用戶屬於團隊has_many用戶。用戶一次只能屬於一個團隊。我希望用戶能夠創建一個團隊,加入一個現有團隊,或者離開他們當前的團隊。以下是我現在在模型,控制器和視圖中的內容,但它不起作用。創建團隊導軌3

此外,我希望創建團隊的人成爲團隊負責人(管理員)。有人可以告訴我如何做到這一點?

用戶模型:

belongs_to :team, dependent: :destroy 


def team_member? 
team.present? 
end 

def join!(team) 
team.create! 
end 

def unjoin!(team) 
team.destroy 
end 

組隊模式:

has_many :users 

attr_accessible :team_name, :team_id 

validates :team_name, presence: true, length: { maximum: 140 } 

default_scope order: 'teams.created_at DESC' 

團隊控制器:

before_filter :signed_in_user 

def join 
    @team = Team.find params[:id] 
    current_user.update_attribute(:team_id, @team.id) 
    redirect_to @team 
end 

def leave 
    @team = Team.find params[:id] 
    current_user.update_attribute(:team_id, nil) 
    redirect_to @team 
end 

    def create 
    @team = Team.new(params[:team]) 
    if @team.save 
     flash[:success] = "Team Created!" 
     redirect_to @team 
    else 
    render 'new' 
    end 
    end 

_join_team_.html.erb

<%= form_for(current_user.team.join) do |f| %> 
    <div><%= f.hidden_field :team_name %></div> 
    <%= f.submit "Join", class: "btn btn-large btn-primary" %> 
<% end %> 

回答

0

協會似乎很好。處理代碼。若要添加「teamlead」,您可以將has_one關聯添加到團隊模型中:

has_one :teamlead, :class => "User", :dependent => :nullify