0

文档显示这是您标记和关联对象以进行销毁的方式,但它不起作用。怎么来的?

文档位于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

我有:

约会.rb

class Appointment < ActiveRecord::Base
  belongs_to :time_block
end

时间块.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
4

2 回答 2

1

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

所以改变 time_block.rb 使用:

has_one :appointment, autosave: 'true'

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

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

于 2018-10-22T03:07:25.453 回答
0

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

has_one :appointment, :dependent => :destroy

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

于 2012-05-30T23:42:39.597 回答