1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/activerecord/test/models/ship.rb
Agis- 19b168e611 Only nullify persisted has_one target associations
Since after 87d1aba3c `dependent: :destroy` callbacks on has_one
assocations run *after* destroy, it is possible that a nullification is
attempted on an already destroyed target:

    class Car < ActiveRecord::Base
      has_one :engine, dependent: :nullify
    end

    class Engine < ActiveRecord::Base
      belongs_to :car, dependent: :destroy
    end

    > car = Car.create!
    > engine = Engine.create!(car: car)
    > engine.destroy! # => ActiveRecord::ActiveRecordError: cannot update a
    >   destroyed record

In the above case, `engine.destroy!` deletes `engine` and *then* triggers the
deletion of `car`, which in turn triggers a nullification of `engine.car_id`.
However, `engine` is already destroyed at that point.

Fixes #21223.
2015-08-24 11:49:43 +03:00

39 lines
1.2 KiB
Ruby

class Ship < ActiveRecord::Base
self.record_timestamps = false
belongs_to :pirate
belongs_to :update_only_pirate, :class_name => 'Pirate'
belongs_to :developer, dependent: :destroy
has_many :parts, :class_name => 'ShipPart'
has_many :treasures
accepts_nested_attributes_for :parts, :allow_destroy => true
accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc(&:empty?)
accepts_nested_attributes_for :update_only_pirate, :update_only => true
validates_presence_of :name
attr_accessor :cancel_save_from_callback
before_save :cancel_save_callback_method, :if => :cancel_save_from_callback
def cancel_save_callback_method
throw(:abort)
end
end
class ShipWithoutNestedAttributes < ActiveRecord::Base
self.table_name = "ships"
has_many :prisoners, inverse_of: :ship, foreign_key: :ship_id
has_many :parts, class_name: "ShipPart", foreign_key: :ship_id
validates :name, presence: true
end
class Prisoner < ActiveRecord::Base
belongs_to :ship, autosave: true, class_name: "ShipWithoutNestedAttributes", inverse_of: :prisoners
end
class FamousShip < ActiveRecord::Base
self.table_name = 'ships'
belongs_to :famous_pirate
validates_presence_of :name, on: :conference
end