mercredi 25 février 2015

How to create record with belongsTo association with ember.js front end and rails back end

I'm trying to create a record that has a belongs_to association. I have a rails back end with an ember front end.


I'm able to create users, but can't figure out how to create posts for users, i.e.,



# rails/db/seeds.rb

user.posts.create(title: "bonjour")


Rails


Here are the rails models



class Post < ActiveRecord::Base
belongs_to :user
end

class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
end


Here is the posts controller:



class Api::PostsController < ApplicationController

...

def update
post = Post.find(params[:id])
post.title = params[:post]['title']
post.save!
render json: post
end

def create
user = User.find(params[:id])
post = user.posts.create(title: params[:title])
render json: post
end

end


Here are the serializers' files



# app/serializers/posts_serializer.rb
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :user_id
end

# app/serializers/user_serializer.rb
class UserSerializer < ActiveModel::Serializer
embed :ids, include: true

attributes :id, :name
has_many :posts
end


Ember


Here are the Ember models



// app/models/post.js

export default DS.Model.extend({
title: DS.attr('string'),
user: DS.belongsTo('user', { async: true})
});

// app/models/user.js

export default DS.Model.extend({
name: DS.attr('string'),
posts: DS.hasMany('post')
});


Here is the create.js file for posts



// app/routes/posts/create.js

export default Ember.Route.extend({

model: function () {
return this.store.createRecord('post', {
title: ''
});
},

actions: {
create: function () {
var my_model = this.controller.get('model');
my_model.save();
this.transitionTo('users.show', my_model);
}
}
});


Here is the create.hbs template



app/templates/posts/create.hbs

<h4 class="create-new-post">Create New Post</h4>

{{input value=title class='post-title'}}

<p><button type='submit' {{action 'create'}} class='commit-post-creation'>Submit</button></p>


And lastly, here is the app/router.js file



...

Router.map(function() {
this.resource('users', function () {
this.route('show', {path: ':user_id'});
this.route('edit', {path: ':user_id/edit'});
this.route('create', {path: 'create'});
});

this.resource('posts', function () {
this.route('show', {path: ':post_id'});
this.route('edit', {path: ':post_id/edit'});
this.route('create', {path: 'create'});
});

});

...


When I try to create a post, I get the error:



POST http://localhost:4200/api/posts 404 (Not Found)


The post shows up at first, but there is no user associated with the post, and then it disappears when the page refreshes.


Thanks. Any help would be really appreciated. I'm just learning Ember, so sorry about the massive post.





Aucun commentaire:

Enregistrer un commentaire