文档显示这是你如何标记和关联对象的破坏,但它不起作用。怎么会?
文档在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
mark_for_destruction
仅在您将autosave: true
添加到模型时才有效。
所以改变time_block.rb来使用:
has_one :appointment, autosave: 'true'
有关更多信息,请参阅https://apidock.com/rails/ActiveRecord/AutosaveAssociation/mark_for_destruction。
仅在为此关联模型启用父级上的:autosave选项时才有用。