标记相关对象以便销毁无效

问题描述 投票:0回答:2

文档显示这是你如何标记和关联对象的破坏,但它不起作用。怎么会?

文档在http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html显示:

member.avatar_attributes = { :id => '2', :_destroy => '1' }
member.avatar.marked_for_destruction? # => true
member.save
member.reload.avatar # => nil

我有:

appointment.rb

class Appointment < ActiveRecord::Base
  belongs_to :time_block
end

time_block.rb

class TimeBlock < ActiveRecord::Base
  has_one :appointment
  accepts_nested_attributes_for :appointment, :allow_destroy => :true, 
                                              :reject_if => :all_blank

end

(rdb:144) @time_block.appointment_attributes = {"_destroy"=>"1", "id"=>"48"}

(rdb:144) p @time_block.appointment.marked_for_destruction?
false
ruby-on-rails ruby-on-rails-3 activerecord
2个回答
0
投票

如果您希望在销毁TimeBlock时销毁约会,请包括:

has_one :appointment, :dependent => :destroy

有关更多信息,请参阅:RailsGuides


0
投票

mark_for_destruction仅在您将autosave: true添加到模型时才有效。

所以改变time_block.rb来使用:

has_one :appointment, autosave: 'true'

有关更多信息,请参阅https://apidock.com/rails/ActiveRecord/AutosaveAssociation/mark_for_destruction

仅在为此关联模型启用父级上的:autosave选项时才有用。

© www.soinside.com 2019 - 2024. All rights reserved.