1
votes

I am having trouble implementing what I understand to be a polymorphic relationship using ember-data rev12.

I have the following models:

App.Project = DS.Model.extend
  lists: DS.hasMany('App.List', { polymorphic: true })

App.Proposal = DS.Model.extend
  lists: DS.hasMany('App.List', { polymorphic: true })

App.Employee = DS.Model.extend
  lists: DS.hasMany('App.List', { polymorphic: true })

App.List = DS.Model.extend
  name: DS.attr('string')
  #project: DS.belongsTo('App.Project', { polymorphic: true })

And I am trying to create a new list from the project router like so.

App.ProjectRoute = Ember.Route.extend
  events:
    newList: (project) ->
      lists = project.get('lists')
      list = App.List.createRecord(name: 'list1')
      lists.pushObject(list)
      @store.commit()

But the request to the server is setting the polymorphic keys incorrectly.

I was expecting the payload to look like:

 { list: { name: list1, listable_type: project, listable_id: 100 } }

But got:

{ list: { name: list1, project_type: project, project_id: 100 } }

What am I missing? Is there a way to define the polymorphic type or key?.


Here is my temporary hack

https://gist.github.com/arenoir/5409904

1

1 Answers

6
votes

First thing, based on the current models you have, you don't need to use polymorphic associations. And you may not want to set the polymorphic option on both end of the relationship.

If you want to have your payload to contain listable, you just need to rename your attribute:

App.List = DS.Model.extend
  name: DS.attr('string')
  listable: DS.belongsTo('App.Project', { polymorphic: true })

UPDATE

Based on my understanding of your classes, it is a List that can belong to different types. So you should define your models like this:

App.Listable = DS.Model.extend
  lists: DS.hasMany('App.List')

App.Project = App.Listable.extend

App.Proposal = App.Listable.extend

App.Employee = App.Listable.extend

App.List = DS.Model.extend
  name: DS.attr('string')
  listable: DS.belongsTo('App.Listable', { polymorphic: true })

and the payload will look like this:

{list: {name: "list1", listable_type: 'project', listable_id: 100}}

I don't know if you also want a list to be added to several listables at the same time. Based on the names of your models, I'm tempted to believe that it's not what you want: a list should contain different objects (project, proposal, employee). and not a project can have multiple lists.