如何使用依赖::在rails中销毁?

时间:2015-04-10 11:54:40

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2

我有2个模型,如下所述。

class EmpGroup < ActiveRecord::Base
  belongs_to :user
  has_many :emp_group_members, dependent: :destroy
end

class EmpGroupMember < ActiveRecord::Base
  belongs_to :emp_group
  belongs_to :user
end

现在问题是每当我试图销毁一个组时,我都会收到如下错误。

PG::ForeignKeyViolation: ERROR:  update or delete on table "emp_groups" violates foreign key constraint "fk_rails_bd68440021" on table "emp_group_members"
DETAIL:  Key (id)=(1) is still referenced from table "emp_group_members".

我缺少什么?

5 个答案:

答案 0 :(得分:20)

为您的EmpGroup模型添加级联删除:

class EmpGroup < ActiveRecord::Base
   has_many :emp_group_members, :dependent => :delete_all
end

或者

您是否正在调用delete方法?你应该拨打destroy。 使用.destroy

答案 1 :(得分:14)

:dependent belongs_to 关联中可用的选项之一

If you set the :dependent option to:

:destroy, when the object is destroyed, destroy will be called on its associated objects.
:delete, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their destroy method.

Additionally, objects will be destroyed if they're associated with dependent: :destroy, and deleted if they're associated with dependent::delete_all。

has_many 关联中的

:destroy causes all the associated objects to also be destroyed
:delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not execute)

你可以尝试

 emp_member_1= @emp_group.emp_group_members.first
 ##delete associated record
 @emp_group.emp_group_members.delete(emp_member_1)

答案 2 :(得分:4)

新语法:

import numpy as np
import requests
from io import BytesIO
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox

def offset_image(x, y, label, bar_is_too_short, ax):
    response = requests.get(f'https://www.countryflags.io/{label}/flat/64.png')
    img = plt.imread(BytesIO(response.content))
    im = OffsetImage(img, zoom=0.65)
    im.image.axes = ax
    x_offset = -25
    if bar_is_too_short:
        x = 0
    ab = AnnotationBbox(im, (x, y), xybox=(x_offset, 0), frameon=False,
                        xycoords='data', boxcoords="offset points", pad=0)
    ax.add_artist(ab)

labels = ['CW', 'CV', 'GW', 'SX', 'DO']
colors = ['crimson', 'dodgerblue', 'teal', 'limegreen', 'gold']
values = 2 ** np.random.randint(2, 10, len(labels))

height = 0.9
plt.barh(y=labels, width=values, height=height, color=colors, align='center', alpha=0.8)

max_value = values.max()
for i, (label, value) in enumerate(zip(labels, values)):
    offset_image(value, i, label, bar_is_too_short=value < max_value / 10, ax=plt.gca())
plt.subplots_adjust(left=0.15)
plt.show()

答案 3 :(得分:1)

删除组时,是使用删除还是销毁。 - 之前我遇到过这个错误,那是因为我有一个错字并使用.delete而不是.destroy

答案 4 :(得分:0)

插入这样的关系

has_many :children, :dependent => :destroy

要了解有关销毁和删除的更多信息,请转到此链接 https://medium.com/@wkhearn/delete-vs-destroy-does-it-even-matter-8cb4db6aa660