一个用户属于一个团队,一个团队拥有_许多用户。一个用户一次只能属于一个团队。我希望用户能够创建团队、加入现有团队或离开当前团队。以下是我现在在模型、控制器和视图中拥有的内容,但它不起作用。
另外,我希望创建团队的人成为团队负责人(管理员)。有人可以告诉我该怎么做吗?
用户模型:
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 %>