我使用的是Rails 4.2.7。当我不再有对象指向孤立实体时,有没有一种方法可以自动删除它?我有这两种型号…
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"实体及其附带地址对象的方法…
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实体以前有一个地址对象,那么该对象将保留在数据库中,尽管它是孤立的。调整内容以便从数据库中删除孤立地址实体的最简单方法是什么?
只需更新您的模型,如下
class MyObject < ActiveRecord::Base
belongs_to :address, :autosave => true
class Address < ActiveRecord::Base
has_one :my_object, dependent: :destroy