【问题标题】:Marking associated object for destruction not working将关联对象标记为销毁不起作用
【发布时间】:2012-05-30 22:11:57
【问题描述】:

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

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

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

【问题讨论】:

  • 我认为你的 TimeBlock 模型中需要has_one :appointment
  • 哦,抱歉,忘记包含它了。更新帖子。

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


【解决方案1】:

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

所以更改 time_block.rb 以使用:

has_one :appointment, autosave: 'true'

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

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

【讨论】:

    【解决方案2】:

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

    has_one :appointment, :dependent => :destroy
    

    更多信息请见:RailsGuides

    【讨论】:

    • 不,我希望在约会属性有 _destroy => true/1 时销毁约会关联
    猜你喜欢
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    相关资源
    最近更新 更多