Skip to content

Instantly share code, notes, and snippets.

@beerlington
Created July 10, 2012 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beerlington/5cad22a11f011052d8f6 to your computer and use it in GitHub Desktop.
Save beerlington/5cad22a11f011052d8f6 to your computer and use it in GitHub Desktop.
# 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