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/bird.rb
Ryuta Kamizono 22360534ac Fix relation.create to avoid leaking scope to initialization block and callbacks
`relation.create` populates scope attributes to new record by `scoping`,
it is necessary to assign the scope attributes to the record and to find
STI subclass from the scope attributes.

But the effect of `scoping` is class global, it was caused undesired
behavior that pollute all class level querying methods in initialization
block and callbacks (`after_initialize`, `before_validation`,
`before_save`, etc), which are user provided code.

To avoid the leaking scope issue, restore the original current scope
before initialization block and callbacks are invoked.

Fixes #9894.
Fixes #17577.
Closes #31526.
2019-02-07 21:04:01 +09:00

24 lines
540 B
Ruby

# frozen_string_literal: true
class Bird < ActiveRecord::Base
belongs_to :pirate
validates_presence_of :name
accepts_nested_attributes_for :pirate
before_save do
# force materialize_transactions
self.class.connection.materialize_transactions
end
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
attr_accessor :total_count
after_initialize do
self.total_count = Bird.count
end
end