用于销毁 has_many 的视图/控制器:通过关联
我有用户、团队和 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。
I've got Users, Teams, and TeamMemberships, which are associated with a has_many :through.
I'm trying add the ability to remove a User from a Team, which requires destroying the TeamMembership model that associates them.
My Models are as follows:
# 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
The view currently looks like this:
- @team.members.each do |member|
.member
= link_to member.name, user_path(member)
= button_to "Remove User"
I'm looking for help with finishing the implementation for the "Remove User" button. I'm not sure how to pass in the TeamMembership that I need to destroy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在用户控制器中:
在视图中,
您也可以
在 team_memberships 控制器中执行销毁操作,
但是即使用户从未单击链接,也需要进行查询才能获取每个成员的 team_membership...
In the users controller:
In the view
You could also just have
And have a destroy action in the team_memberships controller
But there would be a query needed to get the team_membership for each member even if the user never click the link...