Setting an identifier in ember data with createRecord

If I try to create a record with something like

var myObject = App.ModelName.createRecord( data ); myObject.get("transaction").commit(); 

id myObject is never set.

This says that id generation should be handled by EmberData (first answer). So what should be? Where is the new identifier defined. Should there be an API callback to get a valid identifier?

+4
source share
2 answers

An identifier is the primary key for your record, which is created by your database, not Ember. This JSON structure represents a REST message, does not notice the identifier.

 {"post":{"title":"c","author":"c","body":"c"}} 

In your REST Post function, you should get the last insert ID and return it back with the rest of the model data in Ember using the following JSON structure. Note the identifier, which is the last insert identifier. You should get this last insert identifier manually using your DB api.

 {"post":{"id":"20","title":"c","author":"c","body":"c"}} 

This is my sample code for my REST message. I encoded this using the PHP REST Slim framework:

 $app->post('/posts', 'addPost'); //insert new post function addPost() { $request = \Slim\Slim::getInstance()->request(); $data = json_decode($request->getBody()); //logging json data received from Ember! $file = 'json1.txt'; file_put_contents($file, json_encode($data)); //exit; foreach($data as $key => $value) { $postData = $value; } $post = new Post(); foreach($postData as $key => $value) { if ($key == "title") $post->title = $value; if ($key == "author") $post->author = $value; if ($key == "body") $post->body = $value; } //logging $file = 'json2.txt'; file_put_contents($file, json_encode($post)); $sql = "INSERT INTO posts (title, author, body) VALUES (:title, :author, :body)"; try { $db = getConnection(); $stmt = $db->prepare($sql); $stmt->bindParam("title", $post->title); $stmt->bindParam("author", $post->author); $stmt->bindParam("body", $post->body); $stmt->execute(); $insertID = $db->lastInsertId(); //get the last insert ID $post->id = $insertID; //prepare the Ember Json structure $emberJson = array("post" => $post); //logging $file = 'json3.txt'; file_put_contents($file, json_encode($emberJson)); //return the new model back to Ember for model update echo json_encode($emberJson); } catch(PDOException $e) { //$errorMessage = $e->getMessage(); //$data = Array( // "insertStatus" => "failed", // "errorMessage" => $errorMessage //); } } 
+2
source

With some REST adapters, such as Firebase , you can define id as the record variable that you are going to create.

 App.User = DS.Model.extend({ firstName: DS.attr('string') }); var sampleUser = model.store.createRecord('user', { id: '4231341234891234', firstName: 'andreas' }); sampleUser.save(); 

JSON in the database (Firebase)

 "users": { "4231341234891234": { "firstName": "andreas" } } 
+2
source

Source: https://habr.com/ru/post/1486307/


All Articles