I am trying to set up a polymorphic association for a parent that has multiple different types of children. What I find in the documentation is about the inverse problem: children with different types of parents.
I tried the code below, but that always results in productables of type 'Store', while I want them to be 'Book' or 'DVD'.
class App.Product extends Batman.Model
@belongsTo 'productable', {polymorphic: true}
class App.Book extends Product
class App.DVD extends Product
class App.Store extends Batman.Model
@hasMany 'products', {as: 'productable'}
Thanks.
Yes, you're right. Usually, polymorphism is for a case like this:
Now, a
Productwill store bothproductable_idandproductable_type.productable_typewill be eitherStoreorVendingMachine.But... you want to have children of different types available from a single accessor? I don't know that batman.js supports this out of the box, but here's a way you might be able to get it done:
Actually, the docs say not to use
Set::mergeinside accessors, but rather to useBatman.SetUnion. If this approach seems like it would work, you might want to look into that!Then, if you need to send class names back in JSON, you can use
@encodeon your child models, for example:Hope that helps!
Edit:
you could shorthand the relation and accessor, if you think you'll have a lot of them:
Might be worth a shot anyways!