我需要创建用户团队。一个用户属于一个团队(只有一个团队)一个团队有很多用户。我不知道如何让用户能够创建、加入和离开团队。以下是我到目前为止所拥有的,但我确信我做的很糟糕(而且“newby”错了)。
用户模型:
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
团队模式
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'
团队关系模型
attr_accessible :team_id
belongs_to :team
belongs_to :user
validates :team_id, presence: true
路线:
resources :teams do
member do
get 'join'
get 'leave'
end
end
团队控制器:
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
_join_team.html.erb
<%= form_for(current_user.team_relationships.build(team_id: @team_id),
remote: true) do |f| %>
<div><%= f.hidden_field :team_id %></div>
<%= f.submit "Join", class: "btn btn-large btn-primary" %>
<% end %>
_unjoin_team.html.erb
<%= form_for(current_user.team_relationships.find_by_team_id(@team_id),
html: { method: :delete }) do |f| %>
<%= f.submit "Leave Team", class: "btn btn-large" %>
<% end %>
如果你不知道我正试图为此目的调整 Hartl 教程中的一些内容。我究竟做错了什么?
我相信我已经弄清楚了模型,但现在我不确定如何让用户创建团队、摧毁团队、加入团队或离开团队。我必须在模型、控制器和视图中做什么才能实现它?