secret

  • Download Gist
active_record_base_patch.rb
Ruby
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
sti_example.rb
Ruby
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'>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.