vendredi 21 août 2015

Handling Store.save() for records that contains DS.BelongsTo

I have a blog that uses JSON to communicate between Rails with Active Model Serializers v0.10.0.rc2 and Ember.js. Everything was working until I needed to implement DS.BelongsTo on the Post model for getting the tag name from the Genre model.

Most of it (especially server side) seems to be working as {{model.genre.name}) does display the genre name for posts created on the server side (seeds.rb), but things always turns sour when I try to create a post on the Ember side... I tried different ways, but I just can't get the genre_id to be saved with the post. Is the code below correct?

Create.js Controller

var self = this;
var store = this.store;
var post = store.createRecord('post', {
    user_id: this.get('session.secure.userId'),
    ...
    genre: store.find('genre', this.get('genreID'))
});
console.log(post.genre); //>> Computed Property
console.log(post.genre.genre_id); //>> Undefined
console.log(post.genre.id); //>> Undefined
post.set('genre_id', this.get('genreID')); 
console.log(post.genre_id); //>> 1
post.save().then(function() {
    self.transitionToRoute('post', post);
}, function() {
    alert('Failed to create Post...');
});

Terminal

Processing by Api::V1::PostsController#create as JSON

Parameters: {"post"=>{"user_id"=>4, "fact_link"=>"bcvxvbxcbvxc", "fiction_link"=>"vbxcbcvxvbxcvbxc", "title"=>"vbxcxbvbxvccxvb", "importance"=>nil, "soft_delete"=>false, "soft_delete_date"=>nil, "hidden"=>false, "views_count"=>nil, "text"=>"bvxcbvcxbvcxvbxc", "comments_count"=>nil, "genre_id"=>nil, "fact_type_id"=>nil, "category_id"=>nil, "topic_id"=>nil}}

User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = ? LIMIT 1  [["email", "user@example.com"]]
(0.1ms)  begin transaction

SQL (0.2ms)  INSERT INTO "posts" ("text", "views_count", "title", "user_id", "fact_link", "fiction_link", "soft_delete", "hidden", "comments_count", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  [["text", "bvxcbvcxbvcxvbxc"], ["views_count", nil], ["title", "vbxcxbvbxvccxvb"], ["user_id", 4], ["fact_link", "bcvxvbxcbvxc"], ["fiction_link", "vbxcbcvxvbxcvbxc"], ["soft_delete", "f"], ["hidden", "f"], ["comments_count", nil], ["created_at", "2015-08-21 17:27:01.399594"], ["updated_at", "2015-08-21 17:27:01.399594"]]

User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 4]]

SQL (0.1ms)  UPDATE "users" SET "posts_count" = COALESCE("posts_count", 0) + 1 WHERE "users"."id" = ?  [["id", 4]]

(17.5ms)  commit transaction

Genre Model

posts: DS.hasMany('posts', {async: true})
name: DS.attr ('string'),

Post Model

user_id: DS.attr ('number'),
...
genre: DS.belongsTo('genre', {async: true})

The entire source code can be found on my Github, but I could add more code snippets here if necessary.




Aucun commentaire:

Enregistrer un commentaire