How to get the "modelName" of a polymorphic relationship "belongsTo"


#1

My models:

// Attachment model
export default DS.Model.extend({
});

// Image Model
import Attachment from './attachment/model';
export default Attachment.extend({
  src: DS.attr('string)
});

// Doc Model
import Attachment from './attachment/model';
export default Attachment.extend({
  filename: DS.attr('string')
});

// Email Model
export default DS.Model.extend({
  title: DS.attr('string'),
  attachment: belongsTo()
});

In my template, i would like to identify the attachment’s modelName… If my Email has an Image, i can use {{email.attachment.src}}. It’s OK. If it’s a Doc attachment, {{email.attachment.filename}} works. No problem.

But, when i try to display attachment modelName, i can’t… I try:

  • {{email.attachment.constructor.modelName}}
  • {{email.attachment.content.constructor.modelName }}

Only last ( {{email.attachment.content.constructor.modelName }}) works. Why ? I know belongsTo relationship is a DS.PromiseObject so I thought it was possible to use {{email.attachment.constructor.modelName}} !? Why not ?

Thanks for your help.


#2

PromiseObject is an ObjectProxy, and ObjectProxy only forwards properties that are undefined in the proxy object to the object in the content property.


#3

Thank you, it’s so simple :slight_smile:

i found a simple way to get modelName: add a CP in my Attachment model like this:

// Attachment model
export default DS.Model.extend({
  modelName: Ember.computed.alias('constructor.modelName')
});

So i can use {{email.attachment.modelName}} (= “doc” OR “image”).