Skip to content

@beerlington /active_record_base_patch.rb secret
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
# 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
# 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.