Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist
View active_record_base_patch.rb
1 2 3 4 5 6 7 8 9 10 11 12 13
# Override ActiveRecord::Base.new to return an STI subclass if the type field is set.
module ActiveRecord
class Base
class << self
def new(*attributes, &block)
obj = super
model = find_sti_class(obj[inheritance_column])
return obj if obj.is_a? model
obj.becomes(model)
end
end
end
end
View active_record_base_patch.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# STI models
 
class Cat < ActiveRecord::Base
end
 
class FatCat < Cat
end
 
# Before patch:
 
Cat.new {|cat| cat.type = 'FatCat' } # => #<Cat id: nil, type: 'FatCat'>
Cat.where(type: 'FatCat').new # => #<Cat id: nil, type: 'FatCat'>
Cat.where(type: 'FatCat').first # => #<FatCat id: nil, type: 'FatCat'>
 
# After patch:
 
Cat.new {|cat| cat.type = 'FatCat' } # => #<FatCat id: nil, type: 'FatCat'>
Cat.where(type: 'FatCat').new # => #<FatCat id: nil, type: 'FatCat'>
Cat.where(type: 'FatCat').first # => #<FatCat id: nil, type: 'FatCat'>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.