我有用户,小组和TeamMemberships,它们与has_many:through相关联。
我正在尝试添加从团队中删除用户的功能,这需要销毁与其关联的TeamMembership模型。
我的模型如下:
# models/team.rb
class Team < ActiveRecord::Base
has_many :team_memberships, :dependent => :destroy
has_many :members, :through => :team_memberships
end
# models/user.rb
class User < ActiveRecord::Base
has_many :team_memberships
has_many :teams, :through => :team_memberships
end
# models/team_membership.rb
class TeamMembership < ActiveRecord::Base
belongs_to :team
belongs_to :member, class_name: 'User', foreign_key: 'user_id'
end
目前的观点如下:
- @team.members.each do |member|
.member
= link_to member.name, user_path(member)
= button_to "Remove User"
我正在寻找帮助来完成“删除用户”按钮的实现。我不确定如何传递我需要销毁的TeamMembership。
答案 0 :(得分:3)
resources :teams do
resources :users do
member do
delete :remove_from_team
end
end
end
在用户控制器中:
def remove_from_team
@team = Team.find(params[:team_id]) #can do that in before_filter
user = User.find(params[:id])
@team.members.delete user
redirect_to @team
end
在视图中
= button_to "Remove user", remove_from_team_team_user_path(@team, member), :method => :delete
你也可以
resources :team_memberships
并在team_memberships控制器中进行销毁操作
= button_to "Remove user", team_membership_path(@team.team_memberships.where(:user_id => member.id).first), :method => :delete
但是,即使用户从不点击链接,也需要获得每个成员获得team_membership的查询...