【发布时间】:2017-11-05 04:00:31
【问题描述】:
我有经典的has_many: through 关系:
class UserGroup < ApplicationRecord
has_many :user_groups_users
has_many :users, through: :user_groups_users
end
class UserGroupsUser < ApplicationRecord
belongs_to :user_group
belongs_to :user
end
class User < ApplicationRecord
has_many :user_groups_users
has_many :user_groups, through: :user_groups_users
end
为了销毁 UserGroup 记录,我需要销毁 UserGroupsUser 中的相应记录,这两者都是 gem 的一部分。否则我将返回错误,即有用户绑定到用户组,我无法销毁特定的 UserGroup。
目前在我的控制器中我有这个:
def destroy
@user_group = UserGroup.find(params[:id])
UserGroupsUser.where(user_group_id: @user_group).destroy_all
respond_to do |format|
if @user_group.destroy
format.js { flash.now[:notice] = "User group #{@user_group.name} deleted!" }
format.html { redirect_to user_groups_url }
format.json { head :no_content }
else
format.js { flash[:danger] = "User group #{@user_group.name} cannot be deleted because
#{@user_group.users.size} users belong to it" }
end
end
end
但是,当我在视图中单击删除按钮时,它会在我在模态窗口中接受之前破坏记录。 我如何使它在destroy 行动中,请在接受后? .
我在 View 中的“删除”操作很正常:
<%= link_to 'Delete', user_group, method: :delete, remote: true,
data: { confirm: "Do you confirm deleting #{user_group.name}?" }, class: 'btn-danger btn btn-xs' %>
【问题讨论】:
标签: ruby-on-rails ruby activerecord ruby-on-rails-5