Trying To Do A Simple Add Item To FIXTURE - ember.js

I have a simple fixture:
App.User.FIXTURES = [
{ userid: 1, name: 'George', email: 'george#gmail.com', bio: 'Lorem Ipsum', created: 'Jan 5, 2015' },
{ userid: 2, name: 'Tom', email: 'tom#hotmail.com', bio: 'Lorem Ipsum 2', created: 'Jan 15, 2015' },
{ userid: 3, name: 'Mary', email: 'mary#aol.com', bio: 'Lorem Ipsum 3', created: 'Jan 25, 2015' }
];
And I have a simple submit: (snippet)
App.AddController = Ember.ArrayController.extend({
actions: {
save: function () {
App.User.createRecord({ id: 4, userid: 4, name: 'Created person', email: 'sdh', bio: 'my bio', created: '6543456' });
I THINK this is right as I'm not getting an error on createRecord anymore, but now I'm getting an error, any ideas? One more step I'm missing just to shove something into a fixture?
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);

Kingpin2k is correct in that calling createRecord on the UserModel itself is an older way of using Ember Data. If you're using the latest version you should call createRecord from the store object.
Here's what it should look like:
App.AddController = Ember.ArrayController.extend({
actions: {
save: function () {
//Create a new user
var user = this.store.createRecord('user',{
id: 4,
userid: 4,
name: 'Created person',
email: 'sdh',
bio: 'my bio',
created: '6543456'
});
// Saves the new model, but not needed if you're just using FIXTURES
// Making the call shouldn't throw any errors though and is used in the Guide
user.save();
// Now you can find your record in the store
this.store.find('user', 4).then(function(user){
console.info(user);
});
}
}
});
This was tested on:
DEBUG: -------------------------------
DEBUG: Ember : 1.6.0-beta.1+canary.24b19e51
DEBUG: Handlebars : 1.0.0
DEBUG: jQuery : 2.0.2
DEBUG: -------------------------------
I'd recommend reviewing the "Creating a New Model Instance" portion of the Ember getting started guide as they cover this topic there:
http://emberjs.com/guides/getting-started/creating-a-new-model/

Related

Accessing model properties in Controller - Ember

So, I'm trying to access my model properties in controller.
Controller:
dashobards: [
{ id: 12, name: 'test' },
{ id: 17, name: 'test2' },
];
In route I have model named dashboards
return Ember.RSVP.hash({
dashboards: this.store.findAll('dashboard'),
}).then((hash) => {
return Ember.RSVP.hash({
dashboards: hash.dashboards
});
}, self);
I wanna have result in controller like this:
dashboards: [
{ id: 12, name: 'test' },
{ id: 17, name: 'test2' },
{ id: 17, name: 'test1' },
{ id: 20, name: 'test20' },
];
In controller I am trying to access this model like this:
this.dashborads = this.get(model.dashobards)
And it's not working, is there any other way of doing that?
Another update How to access complex object which we get it from server in ember data model attibute,
Created twiddle to demonstrate
define attribute with DS.attr(),
export default Model.extend({
permissions:DS.attr()
});
route file,
model(){
return this.store.findAll('dashboard');
}
Your server response should be like,
data: [{
type: 'dashboard',
id: 1,
attributes: {
permissions: {'name':'role1','desc':'description'}
}
}]
hbs file,
{{#each model as |row| }}
Name: {{row.permissions.name}} <br/>
Desc: {{row.permissions.desc}} <br />
{{/each}}
Update:
Still I am not sure about the requirement, Your twiddle should be minimalized working twiddle for better understanding..anyway I will provide my observation,
1.
model(params) {
this.set('id', params.userID);
const self = this;
return Ember.RSVP.hash({
dashboards: this.store.findAll('dashboard'),
user: this.store.findRecord('user', params.userID)
}).then((hash) => {
return Ember.RSVP.hash({
user: hash.user,
dashboards: hash.dashboards
});
}, self);
}
The above code can be simply written like
model(params) {
this.set('id', params.userID);
return Ember.RSVP.hash({
dashboards: this.store.findAll('dashboard'),
user: this.store.findRecord('user', params.userID)
});
}
Its good to always initialize array properties inside init method. refer https://guides.emberjs.com/v2.13.0/object-model/classes-and-instances/
For removing entry from array,
this.dashboard.pushObject({ 'identifier': '', 'role': '' }); try this this.get('dashboard').pushObject({ 'identifier': '', 'role': '' });.
if possible instead of plain object you can use Ember.Object like
this.get('dashboard').pushObject(Ember.Object.create({ 'identifier': '', 'role': '' }));
For removing entry.
removeDashboard(i) {
let dashboard = Ember.get(this, 'dashboard');
Ember.set(this, 'dashboard', dashboard.removeObject(dashboard[i]));
}
The above code can be written like, since i is an index
removeDashboard(i) {
this.get('dashboard').removeAt(i)
}
Just do return this.store.findAll('dashboard'); in route model hook, and dont override setupController hook, then in hbs you should be able to access model that will represent RecordArray. you can have a look at this answer for how to work with this.

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]
}
]

Emberjs - adding new record to existing array

I'm trying to add a new record to an already existing array of objects.
The form works fine and when I press 'add' on the button, I get the values through.
However, I'm not able to create a new record, I get an error stating
this.init.apply(this, arguments); } has no method 'CreateRecord'".
Thank you for your help.
Here's my code:
App.Store = DS.Store.extend({
revision: 12,
adapter: 'DS.FixtureAdapter'
});
App.AddController = Ember.ObjectController.extend({
content: Ember.Object.create(),
addTo: function(obj){/*
App.Store.createRecord(
App.Post,
{
id: 3,
title: 'Created person',
author: 'dh2',
publishedAt: new Date('12-12-2003')
});*/
alert(JSON.stringify(obj) + "\n" + obj.title);
}
});
App.Post = DS.Model.extend({
title: DS.attr('string'),
author: DS.attr('string'),
publishedAt: DS.attr('date')
});
App.Post.FIXTURES = [
{
id:1,
title: "This is my title",
author: "John Doe",
publishedAt: new Date('12-27-2012')
},
{
id:2,
title: "This is another title",
author: "Jane Doe",
publishedAt: new Date('02-03-2013')
}
];
From inside a controller the store instance of your app is always available because it get's injected in every controller automatically by the framework, so you should access the store like this:
this.get('store').createRecord(App.Post, {...});
This should work correctly and not raise any errors.
Hope it helps.

Ember: how to show related data (Ember data) in handlebars syntax?

See http://jsfiddle.net/cyclomarc/VXT53/6/
I have data in the form of:
publication: {
id: '1',
title: 'first title',
bodytext: 'first body',
author: {
id: '100',
name: 'Jan'
}
},
I want to show in the hbs part the author name. In the publications hbs (showing each publication), I use the following syntax, but that does not work:
{{publication.author.name}}
In the publications/edit hbs (edit of one publication after selection in publications), I use the following syntax, but that does not work:
{{author.name}}
How should I access the embedded data ?
First of, your working fiddle, sorry I ported it to jsbin since I like it more but this does not affect the functionality in any way: http://jsbin.com/ifukev/2/edit
Now to what I've changed, basically what I've done is to define that a App.Author has many publications and a App.Publication belongs to a App.Author and completed the respective FIXTURES:
App.Author = DS.Model.extend({
name: DS.attr('string'),
publications: DS.hasMany('App.Publication'),
didLoad: function () {
console.log('Author model loaded', this);
}
});
App.Publication = DS.Model.extend({
title: DS.attr('string'),
bodytext: DS.attr('string'),
author: DS.belongsTo('App.Author'),
didLoad: function () {
console.log('Publication model loaded', this);
}
});
//FIXTURES DATA
App.Publication.FIXTURES = [
{
id: '1',
title: 'first title',
bodytext: 'first body',
author: 100
},
{
id: '2',
title: 'second title',
bodytext: 'second post',
author: 300
}
];
App.Author.FIXTURES = [
{
id: '300',
name: 'Marc',
publications: [2]
},
{
id: '100',
name: 'Jan',
publications: [1]
}
];
Hope it helps.

ember Uncaught Error: assertion failed: Emptying a view in the inBuffer state

I get this assertion when run the code below:
Emptying a view in the inBuffer state is not allowed and should not
happen under normal circumstances. Most likely there is a bug in your
application. This may be due to excessive property change
notifications.
Link to demo:
http://plnkr.co/edit/s3bUw4JFrJvsL690QUMi
var App = Ember.Application.create({
Store: DS.Store.extend({
revision: 4,
adapter: DS.FixtureAdapter.create()
}),
Router: Ember.Router.extend({
root: Ember.Route.extend({
index: Ember.Route.extend({
route: "/",
connectOutlets: function(router){
var person;
person = App.Person.find(657);
person.addObserver("isLoaded", function() {
return router.get('router.applicationController').connectOutlet("things", person.get("things"));
});
}
})
})
}),
ApplicationController: Em.Controller.extend(),
ApplicationView: Em.View.extend({
template: Em.Handlebars.compile("{{outlet}}")
}),
ThingsController: Em.ArrayController.extend({
thingTypes: (function() {
return App.ThingType.find();
}).property()
}),
ThingsView: Em.View.extend({
template: Em.Handlebars.compile([
'{{#each controller.thingTypes}}',
'{{this.name}}',
'{{/each}}',
'{{#each controller.content}}',
'{{this.title}}',
'{{/each}}'].join(""))
}),
//MODELS
Person: DS.Model.extend({
things: DS.hasMany('App.Thing', {
embedded: true
})
}),
Thing: DS.Model.extend({
description: DS.attr('string'),
thingType: DS.belongsTo("App.ThingType", {
embedded: true
}),
title: (function() {
return this.get("thingType.name");
}).property("description")
}),
ThingType: DS.Model.extend({
name: DS.attr("string")
})
});
App.Person.FIXTURES = [
{
id: 657,
things: [
{
id: 1,
description: "Some text",
thing_type: {
id: 1,
name: "type 1"
}
}, {
id: 2,
description: "Some text",
thing_type: {
id: 2,
name: "type 2"
}
}
]
}
];
App.ThingType.FIXTURES = [
{
id: 1,
name: "type 1"
}, {
id: 2,
name: "type 2"
}, {
id: 3,
name: "type 3"
}
];
Why is this happening?
I was having the same error while trying to load a list of dropdown values from fixtures. What resolved it was overriding queryFixtures on the fixture adapter:
App.FixtureAdapter = DS.FixtureAdapter.extend
latency: 200
queryFixtures: (records, query, type) ->
records.filter (record) ->
for key of query
continue unless query.hasOwnProperty(key)
value = query[key]
return false if record[key] isnt value
true
I probably wouldn't have figured it out had I not set the latency first. Then the error was a bit more descriptive.
a bit late I guess... but I got it to work here:
http://plnkr.co/edit/hDCT4Qy1h5aE6GjM76qp
Didn't change the logic but where its called
I modified your router like this:
Router: Ember.Router.extend({
root: Ember.Route.extend({
index: Ember.Route.extend({
route: "/",
connectOutlets: function(router) {
var person;
router.set('router.applicationController.currentPerson', App.Person.find(657));
}
})
})
})
And created an ApplicationController:
ApplicationController: Em.Controller.extend({
currentPerson: null,
currentPersonLoaded: function() {
this.connectOutlet("things", this.get("currentPerson.things"));
}.observes("currentPerson.isLoaded"),
})
I dont know if this is the output you wished but the bug vanished!