Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
raise "remove me: this bug has been fixed in rails 6" if RAILS6
module PatchPolymorphicCheck
ON_BAD_CREATE = :log
POOP = "💩".freeze
def _handle_create_type(inst, meth, &block)
klass = inst.class
actual = klass.name
expect = inst[klass.inheritance_column]
if expect && actual != expect
msg = "Bad %s called through STI relation. Expected %s, but got %s." \
% [meth, expect, actual]
case ON_BAD_CREATE
when :log
Rails.logger.debug msg
when :deprecate
ActiveSupport::Deprecation.warn msg
when :raise
raise ArgumentError, msg
else
raise ArgumentError, "Bad value: #{ON_BAD_CREATE}"
end
$stderr.print POOP
inst = block[inst]
end
inst
end
def new(attributes = {}, &block)
_handle_create_type(super, :new) do |inst|
inst.becomes inst[inst.class.inheritance_column].constantize
end
end
def create(attributes = {}, &block)
_handle_create_type(super, :create) { |inst| inst.class.find inst.id }
end
def create!(attributes = {}, &block)
_handle_create_type(super, :create!) { |inst| inst.class.find inst.id }
end
end
ActiveRecord::AssociationRelation.prepend PatchPolymorphicCheck
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.