ember data 1.13.8 and ember cli mirage confusion - ember.js

This is my Ember inspector info tab:
I am using ember-cli-mirage and I'm facing issue here.
I am not able to get belongsTo relationship of a model. When I do car.get('user'), I get a promise in result which gets fullfilled but the value is always null.
My user model
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('String'),
car: DS.belongsTo('car',{async: true})
});
My car model
import DS from 'ember-data';
export default DS.Model.extend({
color: DS.attr('String'),
user: DS.belongsTo('user',{async: true})
});
my mirage/config
this.get('/cars',function(db,request) {
var qp = request.queryParams.searchString.toLowerCase();
return {
cars: db.cars.where({'color':qp}),
users: db.users
};
});
I get the list of cars with search color but I don't get the user.
it returns a promise which when fullfilled gives null.
Since I am using ember-data 1.13.8
I tried using this Mirage working with json but then I get error
datum model is not defined error so i guess new json api is not my issue for some reason my ember data uses old json format and original config works.
this.get('/cars', function(db, request) {
return {
data: db.cars.map(attrs => (
{type: 'cars', id: attrs.id, attributes: attrs }
))
};
})
My cars route look like this
model: function(params) {
self = this;
if(!params){
return [];
}
return this.store.findQuery('car',params);
},
I tried
return this.store.findQuery('car',params).then(function(item){
console.log(item.get('user'));
});
but i still got console.log //undefined
I can see user_id in my json returned.
SOLUTION:
found the issue i was saving relationship as user_id = user.id. It should be user=user.id

SOLUTION: found the issue i was saving relationship as user_id = user.id. It should be user=user.id

Related

Accessing Nested JSON in Ember Model

I'm trying to access a particular ID which is nested inside my model to make a belongsTo association. I have no trouble getting what I need in my template, but need image_id within my model. Below is my JSON and current model.
{
content: {
title: 'Title',
header: 'Header',
image_id: 1
}
slug: 'slug',
title: 'Welcome'
}
Here is my current model...
import DS from 'ember-data';
const { attr } = DS;
export default DS.Model.extend({
content: attr(),
title: attr('string'),
});
Hope this makes sense!! Thanks!
I have similar use-cases (mostly a very variable settings paramter that is stored as json in db) and solved it via a custom transform:
// myapp/transforms/json.js
import DS from 'ember-data';
// Converts stringified json coming from database (usually in table-field 'settings') to a POJO
export default DS.Transform.extend({
deserialize: function(serialized) {
return JSON.parse(serialized);
},
serialize: function(deserialized) {
return JSON.stringify(deserialized);
}
});
//myapp/models/myModel.js
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
content: DS.attr('json')
});
Then in your template you should be able to do
{{model.content.image_id}}
Or in controller
let image_id = this.get('model.content.image_id');
or in model
this.get('content.image_id');

Ember.js : Modify request URL

I create an Ember app with a Symfony REST api. I also use the REST adapter for my requests.
I have 2 models in my app : users and their related comments.
I already created CRUD operations for my user properties and now I focus on the CRUD operations for comments.
Model user.js
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
comments: DS.hasMany('comment')
});
Model comment.js
export default DS.Model.extend({
title: DS.attr('string'),
message: DS.attr('string'),
user: DS.belongsTo('user')
});
I have a route which shows all comments (and other data) of a given user. The request loads the user object and his relations. On the view I also have a form and an action to create a new comment for this user.
Route users/get.js
import Ember from 'ember';
export default Ember.Route.extend({
id: null,
model(params) {
this.set('id', params.user_id);
return this.get('store').findRecord('user', params.user_id, {include: 'comments'});
},
});
Route users/get/comments.js
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
return this.modelFor('user.get', params.user_id);
},
});
Controller users/get/comments.js
import Ember from 'ember';
export default Ember.Controller.extend({
newComment: null,
user: null,
init: function() {
this._super(...arguments);
let comment = this.store.createRecord('comment');
this.set('newComment', comment);
},
actions: {
saveComment: function() {
let user = this.get('model');
let comment = this.get('newComment');
comment.set('user', user);
comment.save();
}
}
});
Everything works, except for the request sent to the backend. I loaded the comments from the user, so I expect a call to :
POST http://my-app.local/users/comments/
Instead the call is sent to :
POST http://my-app.local/comments/
Do you know why and how could I correct it ?
Second problem, the model is loaded from the 'user.get' route. This works because the user comes from this route to this page, but... It's doesn't work if the user enters directly the URL for comments. That sound logical, but I have no clue how to correct this problem... Can you help me ?
This can be done by rewrite the CommentAdapter.urlForCreateRecord method. Which affect new comment record requests.
adapters/comment.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
urlForCreateRecord(modelName, snapshot) {
return '/users/comments'; // the url you want
}
});
There are several urlFor... method you might need to customise your url.
Just check out the document
http://devdocs.io/ember/classes/ds.buildurlmixin/methods#urlForCreateRecord

findAll throwing error

I am using a simple findAll query in my ember application ( ember-version: 2.12.0, ember-data-version: 2.12.1 ) and I get the following error:
Assertion Failed: You can no longer pass a modelClass as the first argument to store.buildInternalModel. Pass modelName instead.
I am using the RESTAdapter and RESTSerializer.
Here is my team model:
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
projects: DS.hasMany('project'),
users: DS.hasMany('user'),
members: Ember.computed('users', function() {
return this.get('users.content.length');
}),
leader: DS.belongsTo('user', {
inverse: 'team'
})
});
and my team serializer:
import ApplicationSerializer from './application';
import DS from 'ember-data';
export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin,{
attrs: {
users: { async: true },
projects: { async: true }
}
});
Despite the error, the team objects I requested are in the store. I had no luck in solving this so far.
Actually the problem was in the serializer and the payload from the server. I should have attrs: {users: {embedded: 'always'}} as users where in the payload from the server.

New model instance with hasMany relationship from form data [duplicate]

I am very new at Ember/ED/EmberFire so apologies if this is a trivial question. I am able to save records to Firebase but I am unable to specify relationships to those records in my controller. I am using
DEBUG: Ember : 1.10.0
DEBUG: Ember Data : 1.0.0-beta.12
DEBUG: Firebase : 2.2.3
DEBUG: EmberFire : 1.4.3
DEBUG: jQuery : 1.11.2
I have a model as such:
var Patient = DS.Model.extend({
lastName: DS.attr('string'),
firstName: DS.attr('string'),
encounters: DS.hasMany('encounter', {async: true})
});
var Encounter = DS.Model.extend({
dateOfEncounter: DS.attr('string'),
patient: DS.belongsTo('patient', {async: true})
});
I am simply trying to specify the patient that my newly created encounter object is associated with. This is my controller:
actions: {
registerEncounter: function() {
var newEncounter = this.store.createRecord('encounter', {
dateOfEncounter: this.get('dateOfEncounter'),
patient: this.store.find('patient', '-Jl8u8Tph_w4PMAXb9H_')
});
newEncounter.save();
this.setProperties({
dateOfEncounter: ''
});
}
}
I can successfully create the encounter record in Firebase, but there is no associated patient property. All I get is
https://github.com/firebase/emberfire/issues/232
this.store.find('patient', '-Jl8u8Tph_w4PMAXb9H_') returns a promise.
Try this:
this.store.find('patient', '-Jl8u8Tph_w4PMAXb9H_').then(function(pat) {
var newEncounter = this.store.createRecord('encounter', {
dateOfEncounter: this.get('dateOfEncounter'),
patient: pat
});
newEncounter.save();
});

Accessing relations from templates with ember-data 1.0.0 beta

App.User = DS.Model.extend({
posts: DS.hasMany('post', {async: true})
});
App.Post = DS.Model.extend({
body: DS.attr(),
user: DS.belongsTo('user')
});
App.ProfileRoute = Ember.Route.extend({
model: function(params) {
return this.get('store').find('user', params.user_id)
}
});
and in template
{{#each post in model.posts}}
{{post.body}}
{{/each}}
json for user. I don't want embed posts in user json
{user: { posts: [1, 2, 3] }}
This don't render anything. It receives posts json from server after this error occur
Assertion failed: You looked up the 'posts' relationship on '' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (DS.attr({ async: true }))
In chrome inspector I see all data loaded properly.
How can I solve this? Should I preload all models I want to use in templates?
The model function in your route is missing the return, so the error is being thrown when you try to access model.posts because there is no model.
App.ProfileRoute = Ember.Route.extend({
model: function(params) {
return this.get('store').find('user', params.user_id);
}
});
Have you tried to just write {{#each posts}}?
Worked for my project.
Then write {{body}} within the each block.
Let me know, thanks!