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

时间:2012-05-30 22:11:58

标签: ruby-on-rails ruby-on-rails-3 activerecord

文档显示这是您如何标记和关联对象以进行销毁,但它无法正常工作。怎么样?

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

2 个答案:

答案 0 :(得分:0)

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

has_one :appointment, :dependent => :destroy

有关详情,请参阅:RailsGuides

答案 1 :(得分:0)

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

因此将time_block.rb更改为使用:

has_one :appointment, autosave: 'true'

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

  

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