Reputation: 2080
Say I have models using STI like so:
class MyBase < ApplicationRecord ; end
class MyBase::MySubclass1 < MyBase ; end
class MyBase::MySubclass2 < MyBase ; end
When I lookup records using the base class, the records all load with the class in the type column.
MyBase.all.to_a.map { |record| record.class.name }
# => [MyBase::MySubclass1, MyBase::MySubclass2]
99 times out of 100 this is a good thing, but is it possible to have these records load into their base class instead of the class in the type column? eg
MyBase.first.class
# => MyBase
I'm hoping there's a way to turn it off in the AR query, something like MyBase.where(condition: :something, use_base: true)
...
My use case is that I'm using a gem which expects me to pass it an AR relation, looks at class.name, and breaks when it gets an STI subclass. To avoid patching the gem, I'd like to abide by its limitations and pass it a relation whose records' classes will automatically be coerced into the STI base class when loaded.
Upvotes: 1
Views: 3007
Reputation: 2895
Myclass.all.map{|e| e.becomes(Myclass)}
will give objects of class Myclass regardless the type attribute.
Upvotes: 2