如果我将关系设置为nil并保存,如何销毁子对象?

时间:2021-10-21 19:25:37

I have

我有

class User < ApplicationRecord
  belongs_to :image, optional: true, dependent: :destroy
  ...
end

I tried to set the relation to nil and save, and expected the record in the database to be deleted, but it was not. How can I ensure the child object is deleted to avoid orphans?

我试图将关系设置为nil并保存,并期望删除数据库中的记录,但事实并非如此。如何确保删除子对象以避免孤儿?

irb(main):005:0> u.image
=> #<Image id: 27, file_file_name: "anita-roddick.png", file_content_type: "image/png", file_file_size: 119348, file_updated_at: "2017-10-12 02:08:01", created_at: "2017-06-12 22:11:57", updated_at: "2017-10-12 02:08:02">
irb(main):006:0> u.image = nil
irb(main):007:0> u.save
=> true
irb(main):008:0> u.image
=> nil
irb(main):009:0> i=Image.find 27
=> #<Image id: 27, file_file_name: "anita-roddick.png", file_content_type: "image/png", file_file_size: 119348, file_updated_at: "2017-10-12 02:08:01", created_at: "2017-06-12 22:11:57", updated_at: "2017-10-12 02:08:02">

§ 4.1.2.4 says the only options are :destroy and :delete.

§4.1.2.4说唯一的选择是:destroy和:delete。

http://guides.rubyonrails.org/v5.0/association_basics.html#belongs-to-association-reference

http://guides.rubyonrails.org/v5.0/association_basics.html#belongs-to-association-reference

1 个解决方案

#1


1  

First

第一

The dependent: :destroy will only delete/destroy the dependency when the parent record is destroy. you should use this to get rid of orphan records.

dependent :: destroy只会在父记录被破坏时删除/销毁依赖关系。你应该用它来摆脱孤儿记录。

This is how I would do something like this.

我就是这样做的。

class User < ApplicationRecord
  belongs_to :image, optional: true, dependent: :destroy
  before_save :check_images, :only => [:update]
  ...
  private
  def check_images
    if image_id.nil? && image_id_changed? 
      Image.find(image_id_was).destroy
    end
  end
end

I hope that this can help you and put you in the right tack

我希望这可以帮助你,并使你正确的方针

#1


1  

First

第一

The dependent: :destroy will only delete/destroy the dependency when the parent record is destroy. you should use this to get rid of orphan records.

dependent :: destroy只会在父记录被破坏时删除/销毁依赖关系。你应该用它来摆脱孤儿记录。

This is how I would do something like this.

我就是这样做的。

class User < ApplicationRecord
  belongs_to :image, optional: true, dependent: :destroy
  before_save :check_images, :only => [:update]
  ...
  private
  def check_images
    if image_id.nil? && image_id_changed? 
      Image.find(image_id_was).destroy
    end
  end
end

I hope that this can help you and put you in the right tack

我希望这可以帮助你,并使你正确的方针