Zespoły użytkowników szyny aplikacji
Muszę tworzyć zespoły użytkowników. Użytkownik należy do zespołu (tylko jeden zespół), zespół ma wielu użytkowników. Nie wiem, jak zmusić użytkownika do tworzenia, dołączania i opuszczania zespołu. Poniżej przedstawiam to, co mam do tej pory, ale jestem pewien, że robię coś strasznie (i „źle” źle).
Model użytkownika:
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
model zespołu
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'
model relacji zespołowej
attr_accessible :team_id
belongs_to :team
belongs_to :user
validates :team_id, presence: true
trasy:
resources :teams do
member do
get 'join'
get 'leave'
end
end
controller_controller:
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 %>
Jeśli nie możesz powiedzieć, że próbowałem w tym celu dostosować część tego, co jest w tutorialu Hartla. Co ja robię źle?
Wierzę, że udało mi się znaleźć modele, ale teraz nie jestem pewien, jak skłonić użytkownika do utworzenia zespołu, zniszczenia zespołu, dołączenia do zespołu lub opuszczenia zespołu. Co muszę zrobić w modelach, kontrolerach i widokach, aby tak się stało?