I'm working with Emeber.js framework; I've created an object like this:
myApp.user=Ember.Object.extend({
name:null,
state:false
});
I've also defined an Ember model this way:
myApp.Wuser = DS.Model.extend({
nome: DS.attr('string'),
user: DS.attr('mycustomtype') // i want put here a mycustom type (user)
});
The question is: how can I create a record? I've tried to write this:
myApp.Wuser.createRecord({nome:"aaa",user:myApp.user.create()});
but an error occurred; do you know how to create a record and how to read it?
Thanks in advance!
You create a record on your store.
record = this.get('store').createRecord(MyApp.User, {name: 'Luke'})
To persist it to your server:
this.get('store').commit();
You can also do this for a transaction:
record = transaction.createRecord(MyApp.User, {name: 'Luke'})
Related
I have a weird problem with mongoose, and I'm starting to suspect that I'm doing something wrong.
My schema looks something like this:
var personSchema = mongoose.Schema({
name: String, // Self-e
info: { type: Object, default: {'value':'result'} },
created_on: { type: Date, default: Date.now }
})
After fetching the document, I've tried to edit the info object like so (pretending that person is the fetched document):
person.info['value2'] = 'result2'
person.save()
These changes don't show up in the DB, and I'm getting no errors when running it. Any ideas?
As I learned from #ippi, because info is a mixed Object, you need to make sure that Mongoose knows it was modified so that it will save when you call person.save()
For example:
person.info['value2'] = 'result2'
person.markModified('info')
person.save()
I'm new to Emberjs, and I'm trying to get my head around how to get data out of my model.
Here's the data structure as its being returned from my server
candidate: {
image: [image],
user: {
name: [User Name]
},
agent: {
phone: [phone]
team: {
name: [Team Name]
}
user: {
name: [User Name]
}
}
}
I cant get ember to recognize any associations more than one level deep.
heres my candidate controller
App.CandidateController = Ember.ObjectController.extend({
location: function() {
var address = this.get('address');
var city = this.get('city');
var state = this.get('state');
var zip = this.get('zip');
return address + ' ' + city + ' ' + state + ', ' + zip;
}.property('address', 'city', 'state', 'zip')
});
App.CandidateSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
agent: {embedded: 'always'},
user: {embedded: 'always'}
}
});
This allows me to get one level deep, but I need two or three levels of association.
Is there a different way to go about it?
I thought organizing everything on the server the way I want it displayed, and just returning the data as its supposed to be rendered to ember, but I have a feeling I'll run into problems when trying to update the models.
Any help is appreciated.
/****** UPDATE *******/
I have refactored my code and I am now returning data from the serializer like this:
{
candidate: {
// relevant fields
},
agent: {
//relevant fields
},
team: {
// relevant fields
}
user: [
{ // candidate user fields },
{ // agent user fields }
]
};
However, data is still not available in my template. In the Ember chrome extension, in the data tab, I get
candidate: (1)
agent: (0)
team: (0)
user (2)
I can see candidate and user data, but not agent or team data. In my candidate model, I have:
App.Candidate = DS.Model.extend({
// other fields
user_id: DS.attr('number'),
agent_id: DS.attr('number'),
user: DS.belongsTo('user'),
agent: DS.belongsTo('agent')
});
It doesn't seem like the belongsTo association actually does anything.
So the first issue is that I'm not getting the correct data, the second issue, and the one that makes me think I am going about this incorrectly, is that I have two users information that I need to display in the template. The first is user information associated with the candidate, and the second is user information that is associated with the agent. Both data need to appear in the same template. Since there is no hierarchy to the data, how would the template know which user info to display in each location?
Again, I think Im thinking about this whole thing incorrectly.
Thanks for your help.
Ember data expects models in a JSON response to be flat, and it's the job of the Serializer to transform your server response into that format. Associations usually are done by ids. The second level is not working because Ember needs to turn each level into an Ember.Object in order to observe property changes.
It might help to look over the JSON conventions portion of the guides. You can also plug your models into the ember data model maker and see what your responses should look like. Finally, make sure you're using the ember-inspector Chrome extension. When I am debugging ember-data related issues, it's usually easiest to just stop after the model hook returns, look in the inspector's store tab, and examine what data has been loaded.
I have started working with EmberJS and Ember-Data, but I've run into a small problem.
I have an application where my data source uses a non-id as the primary key (e.g. /model/<slug_name>). I am using the FixtureAdapter to handle things until I connect it to the backend:
App.ApplicationAdapter = DS.FixtureAdapter.extend({})
App.MyModel = DS.Model.extend({
slug: DS.attr('string'),
body: DS.attr('string')
});
App.MyModel.FIXTURES = [{
slug: 'test-slug',
body: 'Body goes here'
}];
There seem to be several sources of information that explain how to use a different primary key, but they are all oriented around working with the actual data source (and involve modifying the serializer; something that isn't used when working with FixtureAdapter).
If I do the naive thing and just wire up routes...
// ...
App.MyModelEditRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('mymodel', params.slug)
}
});
... and change the template...
{{#link-to "mymodel.edit" slug}}Edit{{/link-to}}
...then I get this error:
Assertion failed: You made a request for a mymodel with id test-slug, but the adapter's response did not have any data
How can I use a non-'id' field as the primary key when working with a FixtureAdapter?
Ideally, is there a solution that works when using a FixtureAdapter or a real data source?
For reference, these are the versions of EmberJS and Ember-Data that I am using:
"ember": "~1.3.2",
"ember-data": "~1.0.0-beta.8"
I'll have to look back for the fixture adapter/serializer, but in the rest adapter/serializer you can define the primary key on the serializer. Within the app, it'll just be known as id, but when it deserializes/serializes it will transform it to the primary key name
App.ColorSerializer = DS.RESTSerializer.extend({
primaryKey: 'piano'
});
App.Color = DS.Model.extend({
color: DS.attr()
});
Example: http://emberjs.jsbin.com/OxIDiVU/774/edit
I’m trying to setup an model association using MEAN where an Epic has many Tasks. I’m creating the Epic first then associating it when creating a task. The task data model looks like this with the Epic associated:
task:
{ name: 'my first task',
epic:
{ name: 'My fist epic',
_id: 52f511c605456ba4c936180d,
__v: 0},
_id: 52f511d605456ba4c936180e,
__v: 0 } }
In my public Epics controller I’m trying to query for all the tasks with the current Epic’s ID but I’m I’m not having much luck. The query below returns ALL tasks instead of the tasks associated with my Epic.
Tasks.query({“epic._id": $routeParams.epicId}, function(tasks) {
$scope.tasks = tasks;
});
Is there a better way to do association and retrieval using MEAN? I’m a bit of a noob.
Thanks in advance!
EDIT:
I've playing around with the idea of updating the epic when a new task is created. In app/controllers/tasks.js I have this code that doesn't work.
exports.create = function (req, res) {
var task = new Task(req.body)
Epic.find(req.body.epic.id, function (err, epic) {
if (err) return next(err)
epic.tasks.push(task.id);
epic.save();
})
task.save()
res.jsonp(task)
}
Are you also using mongoose? I would use the "ref" and "populate".
First you have a TaskSchema.
var TaskSchema = new Schema({ ... });
mongoose.model('Task', TaskSchema);
add the model etc, then you you reference it in your other schema. I'll add an example of 1 or multiple task(s).
var Schema = new Schema({
task: {
type: Schema.ObjectId,
ref: 'Task'
},
tasks: [
{ type: Schema.Types.ObjectId, ref: 'Task'}
]
});
and then to call it with populate.
this.findOne({
_id: id
}).populate('tasks').exec(cb);
It looks like you need help debugging xhr. Let's trace the steps:
Is your request making it to the server?
Is it arriving at the correct express route?
Is your server-side code performing the correct find operation against Mongo?
Is Mongo returning the right results?
Are you writing the results from Mongo into the response correctly?
Are you able to see the response on the client by inspecting the network traffic using your browser's dev tools?
Are you handling the promise success correctly?
You'll need to post more info and code to know where the problem lies.
I'm confused about send collection or model to the server.
This is my model:
var Person = Backbone.Model.extend({
defaults : {},
initialize : function() {}
});
and this is my collection:
var Usercollection = Backbone.Collection.extend({
model : Person,
url : 'https://api.parse.com/1/classes/_User/'
});
Now, if I would save a model on the server I have first to add in a collection and use save on model or first add in a collection and use save on collection? And least, I have to write an ajax call to post the collection or model in a server?
You should save your model to server.
Save a model: Call save() on model e.g.
var user = new UserModel();
user.save({name: 'SJ', age:'35'}, {
success: function (user) {
// I get a model here with id
}
});
Read these links for more information.
How to save your model data: SO Link
Sample code - by Thomas Davis in his screencast # backbonetutorials.com - Must watch
Server side code for wine cellar app
I have given you the link of server side code to have a look at the APIs to make things more meaningful to you. Hope this helps!
If you want to add the model to the collection after the model is saved, you need to use .create on the collection , which fires the add event on the collection after it gets created..
this.collection.create(model.toJSON() , options);
Use collection.create();
http://backbonejs.org/#Collection-create
Convenience to create a new instance of a model within a collection.
Equivalent to instantiating a model with a hash of attributes, saving
the model to the server, and adding the model to the set after being
successfully created. Returns the new model. ...
var Library = Backbone.Collection.extend({
model: Book
});
var nypl = new Library;
var othello = nypl.create({
title: "Othello",
author: "William Shakespeare"
});