2

我正在使用 Rails 4.2.7。当我不再有指向它的对象时,有没有办法自动删除孤立实体?我有这两个模型……</p>

class MyObject < ActiveRecord::Base
  belongs_to :address, :autosave => true, dependent: :destroy


class Address < ActiveRecord::Base
  has_one :my_object

在我的 PostGres“my_objects”表中,我有一个“address_id”列,它是地址表的外键。下面是我用来保存“MyObject”实体及其随附地址对象的方法……</p>

  def save_with_address(params)
    transaction do
      if !params[:address].nil?
        # Address isn't an object yet, it is just a bunch of parameters
        params[:address][:state] = params[:address][:state].nil? ? nil : State.find_by_id(params[:address][:state])
        params[:address][:country] = params[:address][:country].nil? ? nil : Country.find_by_id(params[:address][:country])
        address = Address.new(params[:address])
        address.user = self
        address.save
        self.address = address
      end

      # Save the object
      save
    end
  end

但我注意到,如果 my_object 实体之前有一个地址对象,则该对象仍保留在数据库中,尽管它是孤立的。调整事物以便从数据库中删除我的孤立地址实体的最简单方法是什么?

4

1 回答 1

0

只需如下更新您的模型

class MyObject < ActiveRecord::Base
  belongs_to :address, :autosave => true


class Address < ActiveRecord::Base
  has_one :my_object, dependent: :destroy
于 2016-07-27T14:30:07.227 回答