本文介绍了Rails 5.1 .:销毁“ has_many:through”中的记录与限制相关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有经典的 has_many:通过关系:

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 中的适当记录宝石的一部分。否则,我将得到一个错误消息,即有用户绑定到用户组,并且我无法销毁特定​​的 UserGroup

and in order to destroy UserGroup record, I need to destroy appropriate records in UserGroupsUser, which both is part of a gem. Otherwise I will get back error that there are Users tied to UserGroups and I cannot destroy particular UserGroup.

在我的控制器中,我有以下内容:

At the moment in my Controller I have this:

  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 动作,请在接受后查看?因为我不了解,它会要求接受后才能进行销毁在中通过模型记录,然后在 UserGroup 中记录。

however when I click Delete button in View, it destroys a record before I accept that in my modal window. How do I make it do destroy action, after accept in view, please? As I undestand it would require that after accept, it would firs destroy records in through models and then UserGroup.

我的View中的删除操作非常正常:

My "Delete" action in View is quite regular:

<%= link_to 'Delete', user_group, method: :delete, remote: true, 
data: { confirm: "Do you confirm deleting #{user_group.name}?" }, class: 'btn-danger btn btn-xs' %>


推荐答案

只需更改 has_many:user_groups_users has_many:user_groups_users,:dependent => :destroy

更多信息请参见。

编辑:您说的是宝石。仍然不是问题!找到该类,然后将其添加到初始化程序中(我知道,我知道有更好的地方,但是为了继续进行下去):

You said it was in a gem. Not an issue, still! Find the class, and add this in an initializer (I know, I know, there are better places, but for the sake of moving on from this):

Whatever::To::UserGroupThing.class_eval do 
  has_many :user_group_users, :dependent => :destroy 
end 

但是,如果进行某些更改,维护可能不是您的朋友

But maintenance may not be your friend here if there's some sort of change to the association made down the line by the maintainer.

您也可以在user_group.rb中使用before_destroy钩子。

You could also use a before_destroy hook in user_group.rb

before_destroy do 
  UserGroupUser.where(:user_group => self).destroy_all
end

这篇关于Rails 5.1 .:销毁“ has_many:through”中的记录与限制相关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 22:51