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
Tekin Suleyman 5a3e34ed1d
Ensure Contextual validations fire on associations
If a custom validation context is used, the validations on dependent
association records should fire regardless of whether those record have
`changed_for_autosave?` or not as the use of a custom validation context
increases the chance that validations for the context will be different
to those from when the record was first saved.

6ea80b6 changed the autosave behaviour for single associations such that
validations would only fire on an associated record if the record was
`changed_for_autosave?`. This brought the behaviour inline with that for
collection associations, but introduce a regression in that validations
would no longer fire on dependent associations, even when using a custom
validation context.

This change updates the behaviour for both single and collection
associations.

This commit also updates another related regression test that became a
potential false-positive when 6ea80b6 was merged. The original test was
written to protect against non-custom validations firing on associations
(see #14106). At the time validations on autosaving singular
associations would always fire, even when the association was not dirty,
whereas after 6ea80b6 the validations only fire if the association is
dirty. This update to the test makes the association record dirty to
ensure the validations will fire so that the code responsible for
excluding non-custom contexts is correctly exercised.
2019-10-04 12:17:53 +01:00

42 lines
1.3 KiB
Ruby

# frozen_string_literal: true
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, if: -> { true }
validates :name, presence: true, if: -> { 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, foreign_key: :pirate_id
validates_presence_of :name, on: :conference
end