-
-
Save beerlington/5cad22a11f011052d8f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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