1

I am trying to set a polymorphic association. Unfortunately, the Ember docs don't cover this too well.

My API (Rails) has the following definition:

class User < ActiveRecord::Base
  belongs_to :profile, polymorphic: true#, dependent: :destroy
end

class MemberProfile < ActiveRecord::Base
  has_one :user, as: :profile, dependent: :destroy
end

class GuestProfile < ActiveRecord::Base
  has_one :user, as: :profile, dependent: :destroy
end

Which means, in Rails console, I can do User.last.profile, which will return either a MemberProfile or GuestProfile object.

How should I define this on the client side (Ember)?

// app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
  profile:      DS.belongsTo('profile', { polymorphic: true, async: true })
});

// app/models/member-profile.js
import DS from 'ember-data';
export default DS.Model.extend({
  profile:      DS.belongsTo('profile', { polymorphic: true, async: true })
});

// app/models/guest-profile.js
import DS from 'ember-data';
export default DS.Model.extend({
  profile:      DS.belongsTo('profile', { polymorphic: true, async: true })
});
Christian Fazzini
  • 19,613
  • 21
  • 110
  • 215

1 Answers1

2

You're right, the Ember Docs seem to be lacking. I don't think there's much to it, beyond the DS.belongsTo('profile', { polymorphic: true, async: true }) that you've already outlined.

One option would be to extend a Profile class:

// Standard Ember code - use export/import conventions for ember-cli
App.Profile = DS.Model.extend({
  // Attributes here, maybe a reference to the related User
});

App.MemberProfile = App.Profile.extend({
  // Member-specific attributes
});

App.GuestProfile = App.Profile.extend({
  // Guest-specific attributes
});

App.User = DS.Model.extend({
  profile: DS.belongsTo('profile', {polymorphic: true, async: true})
});

This would allow you to do someUser.get('profile'), and have the returned value be either a member or a guest. It is based off code provided at: http://www.toptal.com/emberjs/a-thorough-guide-to-ember-data#the-ember-data-value-proposition

You could alternatively create similarly-formed Mixins, in a situation that calls for it.

There was a related discussion on the Ember forums earlier this year related to best practices using Ember's polymorphic associations: http://discuss.emberjs.com/t/cleaner-way-to-define-polymorphic-associations/6369

As a side-note, in your javascript code the member-profile.js and guest-profile.js would link to a user, rather than a profile to mimic your Rails code.

DRobinson
  • 4,441
  • 22
  • 31