ember data only with a belongsto relationship - ember.js

here is a working jsbin: http://emberjs.jsbin.com/EnOqUxe/71/edit
What i´d like to have is there the company doesn´t need any reference to the person.
non working code
App.Company.FIXTURES = [
{ id: 1, name: 'Microsoft'},
{ id: 2, name: 'Apple'}
];
App.Person.FIXTURES = [
{ id: 1, name: 'Steve Jobs', company:2},
{ id: 2, name: 'Bill Gates', company:1},
{ id: 3, name: 'Steve Ballmer', company:1}
];
How can i achieve this?
thank you

You're practically there. You just need to fix up the models a bit:
App.Company = DS.Model.extend({
name: DS.attr('string')
});
App.Person = DS.Model.extend({
name: DS.attr('string'),
company: DS.belongsTo('company', {async:true})
});
And change your model hook, since now you link to companies through people, not people through companies.
App.IndexRoute = Ember.Route.extend({
model: function() {
return this.store.find('person');
}
});
http://emberjs.jsbin.com/EnOqUxe/72/edit

Related

How to load dependencies in Ember Data

I have an application, with 2 models: Team and User. Each team has many users, and only 1 Team Leader. On the Index view for Teams, I want to display the list of Teams, and the name of the Team leader. I can't get the name of the team leader to be displayed. Not sure what's wrong.
User Model:
export default Model.extend({
firstName: attr(),
lastName: attr(),
team: belongsTo('team', { inverse: 'users' }),
fullName: Ember.computed('firstName', 'lastName', function() {
return `${this.get('firstName')} ${this.get('lastName')}`;
})
});
Team Model:
export default Model.extend(Validations, {
name: attr(),
shortName: attr(),
description: attr(),
teamLeader: belongsTo('user', { inverse: null }),
users: hasMany('user'),
specialisationArea: attr(),
sourceEnergyTeam: attr(),
isEnergyTeam: Ember.computed('specialisationArea', function(){
return this.get('specialisationArea') == 101;
})
});
Team Index Route:
export default Ember.Route.extend({
model() {
return this.store.findAll('team');
}
});
Team List Template:
{{#each model as |team|}}
<tr>
<td>{{team.name}}</td>
<td>{{team.shortName}}</td>
<td>{{team.description}}</td>
<td>{{team.teamLeader.fullName }}</td>
<td>{{#link-to "teams.team" team}}Details{{/link-to}}</td>
</tr>
{{/each}}
And this is the mirage configuration:
this.get('/teams', () => {
return [{
id : 11,
type: 'team',
name: 'Energy',
description: 'energy desc',
shortName: 'short',
teamLeader: 12,
users: [12],
energyTeam: true
}];
});
this.get('/teams/:team_id', () => {
return {
id: 11,
type: 'team',
name: 'energy',
description: 'energy desc',
shortName: 'eg',
teamLeader: 12,
users: [12],
energyTeam: true
};
});
this.get('/users', () => {
return [{
id: 12,
type: 'user',
firstName: 'Pedro',
lastName: 'Alonso',
team: 11
}];
});
I'm not sure what's going wrong, but in the network calls I can see that only a call to '/teams' is being triggered. Any ideas?
Thanks

Ember Data: saving polymorphic relationships

I'm having trouble saving "hasMany" polymorphic records in Ember Data (1.0.0-beta.15). It looks as if Ember Data isn't setting the "type" property of the polymorphic relationship. Relationships in serialized records look like:
"roles": ["1", "2"]
When I expect them to look more like:
"roles":[{
"id": "1",
"type": "professionalRole"
}, {
"id": "2",
"type": "personalRole"
}
];
I see the following error in the console:
TypeError: Cannot read property 'typeKey' of undefined
If the records come back from the server in the expected format, all is well. The error only occurs when Ember Data creates the relationship.
I experience this using the FixtureAdapter, LocalStorageAdapter, and the RESTAdapter. I've read every piece of documentation I can find on the subject, but I cannot see my mistake.
I've created a CodePen to demonstrate the problem, but I'll also paste that code below.
window.App = Ember.Application.create();
App.ApplicationAdapter = DS.FixtureAdapter;
App.Person = DS.Model.extend({
name: DS.attr(),
roles: DS.hasMany('role')
});
App.Role = DS.Model.extend({
title: DS.attr(),
person: DS.belongsTo('person', {
polymorphic: true
})
});
App.ProfessionalRole = App.Role.extend({
rank: DS.attr()
});
App.ApplicationRoute = Ember.Route.extend({
setupController: function(controller) {
var person = this.store.createRecord('person', {
name: 'James'
});
var role = this.store.createRecord('professionalRole', {
title: 'Code Reviewer',
rank: 'Expert'
});
var promises = Ember.RSVP.hash({
person: person.save(),
role: role.save()
});
promises.catch(function() {
controller.set('initialSaveResult', 'Failure');
});
promises.then(function(resolved) {
controller.set('initialSaveResult', 'Success!');
var resolvedPerson = resolved.person;
var resolvedRole = resolved.role;
// Either/both of these break it
//resolvedRole.set('person', resolvedPerson);
resolvedPerson.get('roles').addObject(resolvedRole);
var innerPromises = Ember.RSVP.hash({
person: resolvedPerson.save(),
role: resolvedRole.save()
});
innerPromises.catch(function() {
controller.set('secondSaveResult', 'Failure');
});
innerPromises.then(function() {
controller.set('secondSaveResult', 'Success!');
});
});
}
});
App.ApplicationController = Ember.Controller.extend({
initialSaveResult: "Loading...",
secondSaveResult: "Loading..."
});

HasMany Polymorphic Relationship In Ember Data

I'm really struggling to understand how polymorphic relationships worm in Ember Data (Beta 11) and cannot find any update information on how to set them up and what is expected in the JSON payload. I'm trying to create a feed of items (think facebook feed) where you have different types of items in the feed. My modeling looks something like the following.
App.Feedable = DS.Model.extend({
activities: DS.hasMany('activity')
});
App.Activity = DS.Model.extend({
feedable: DS.belongsTo('feedable', { polymorphic: true, async: false })
});
App.MemberLikeShare = DS.Model.extend({
status: DS.attr('string')
});
App.PhotoShare = DS.Model.extend({
status: DS.attr('string'),
photo: DS.attr('string')
});
When I do a fetch at /activities I send back JSON that looks like the following:
{
activities: [
{
id: 1,
feedable: { id: 1, type: 'memberLikeShare' }
},
{
id: 4,
feedable: { id: 4, type: 'memberLikeShare' }
},
{
id: 5,
feedable: { id: 5, type: 'photoShare' }
}
],
member_like_shares: [
{
id: 1,
status: 'Foo'
},
{
id: 4,
status: 'Bar'
}
],
photo_shares: [
{id: 5, photo: 'example.jpg'}
]
}
When this runs I get an error like:
You can only add a 'feedable' record to this relationship Error: Assertion Failed: You can only add a 'feedable' record to this relationship
I'm assuming my relationships are wrong or I'm sending the wrong JSON?
polymorphic relationships should extend the base type.
App.Feedable = DS.Model.extend({
activities: DS.hasMany('activity')
});
App.MemberLikeShare = App.Feedable.extend({
status: DS.attr('string')
});
App.PhotoShare = App.Feedable.extend({
status: DS.attr('string'),
photo: DS.attr('string')
});
I'd also expect them to define the activities on them.
member_like_shares: [
{
id: 1,
status: 'Foo',
activites: [1,2,3,4]
},
{
id: 4,
status: 'Bar',
activites: [1,2,3,4]
}
],
photo_shares: [
{
id: 5,
photo: 'example.jpg',
activites: [1,2,3,4]
}
]

createRecord with ember-data + ember-data-django-rest-adapter

I'm currently working on creating an ember application using ember/ember-data/ember-data-django-rest-adapter with Django backend.
I'm having issue creating record when there's belongsTo and hasMany relationship going on.
I currently have this code:
App.Article = DS.Model.extend({
title: attr(),
description: attr(),
authors: hasMany('author'),
category: belongsTo('page'),
slug: attr(),
content: attr(),
articleContent: Ember.computed.alias("content"),
published: attr(),
publish_from: attr(),
isScheduled: function() {
return moment().isBefore(moment(this.get('publish_from')));
}.property('publish_from'),
articlePublishDate: function() {
return moment(this.get('publish_from')).format('MMMM Do YYYY');
}.property('publish_from'),
articlePublishTime: function() {
return moment(this.get('publish_from')).format('h:mm a');
}.property('publish_from'),
//content_type: belongsTo('content_type', { async: true }),
content_type: attr()
});
App.Page = DS.Model.extend({
title: attr(),
description: attr(),
pageContent: attr(null, {
key: 'content'
}),
templateFile: attr(null, {
key: 'template'
}),
slug: attr(),
tree_path: attr(),
tree_parent: belongsTo('page'),
site: attr()
});
App.Author = DS.Model.extend({
name: attr(),
slug: attr(),
description: attr(),
text: attr(),
email: attr(),
photo: attr(),
user: belongsTo('user'),
});
// create article
App.ArticleCreateController = Ember.ObjectController.extend({
editMode: false,
allAuthors: function() {
return this.store.find('author');
}.property(),
allPages: function() {
return this.store.find('page');
}.property(),
actions: {
save: function(session) {
var self = this;
var article = this.get('model');
var newArticle = this.store.createRecord('article', {
content_type: "19",
content: article.get('articleContent'),
description: article.get('description'),
publish_from: article.get('publish_from'),
published: article.get('published'),
slug: article.get('slug'),
title: article.get('title')
});
this.store.find('page', 3).then(function(page) {
newArticle.set('category', page);
});
newArticle.save();
}
}
});
All I really want to do is POST data like this to apiRoot/articles/ (along with other attributes, but those are working the way they should)
authors: [1,3,5], // hasMany
category: 3 // belongsTo
But when I make a POST request, category returns as null for some reason. All I want to extract from it is just the id itself. Also, I have no clue how to extract the array of authors. I tried posting the data, and it tells me something about it needing to be 'App.Author'.
First, at the current time you need a fork of ember-data because async create is currently broken (as it's a promise and the internal serializer won't wait for it to resolve).
Pull down this branch, do a npm install + grunt test to build the adapter. Also you need to use the forked build of ember-data in that branch'es test lib directory (until ember-data pulls in the fix for this)
https://github.com/toranb/ember-data-django-rest-adapter/tree/asyncBelongsToHasManyWIP
Then inside your controller you can do something like this to "create" the customer and appointment (notice -async belongsTo/hasMany relationship)
App.Customer = DS.Model.extend({
name: DS.attr('string'),
appointments: DS.hasMany('appointment', { async: true})
});
App.Appointment = DS.Model.extend({
details: DS.attr('string'),
customer: DS.belongsTo('customer', { async: true})
});
var customer = {
name: 'foobar'
}
this.store.createRecord('customer', customer).save().then(function(persisted) {
var appointment = {
details: 'test',
customer: persisted
}
return self.store.createRecord('appointment', appointment).save().then(function(apt) {
persisted.get('data').appointments.pushObject(apt);
router.transitionTo('index');
});
});

Find record from belongsTo association in Ember.js

How can I get the associated record from an Ember model? Or: how to get the record from the Promise Object?
Customer model
Docket.Customer = DS.Model.extend({
name: DS.attr('string'),
initial: DS.attr('string'),
description: DS.attr('string'),
number: DS.attr('string'),
archived: DS.attr('boolean'),
projects: DS.hasMany('project',{ async: true })
});
Project model
Docket.Project = DS.Model.extend({
name: DS.attr('string'),
description: DS.attr('string'),
number: DS.attr('string'),
archived: DS.attr('boolean'),
customer: DS.belongsTo('customer', { async: true })
});
Find method
var project = this.store.find('project', id).then(function(data) {
console.log(data.get('customer').toString());
});
Console output
<DS.PromiseObject:ember654>
JSON response
{"projects":[
{
"id":1,
"name":"test",
"number":"a310",
"description":null,
"archived":false,
"customer_id":22
}
]};
use another then on the get :)
var project = this.store.find('project', id).then(function(data) {
data.get('customer').then(function(c){
console.log(c);
}
});