我试图创建一个具有belongs_to关联的记录。我有一个带有余烬前端的导轨后端。
我能够创建用户,但无法弄清楚如何为用户创建帖子,即
# rails/db/seeds.rb
user.posts.create(title: "bonjour")
滑轨
以下是铁轨模型
class Post < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
end
这是帖子控制器:
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
以下是序列化程序&#39;文件
# 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模型
// 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')
});
以下是帖子的create.js文件
// 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);
}
}
});
这是create.hbs模板
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>
最后,这是app / router.js文件
...
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'});
});
});
...
当我尝试创建帖子时,我收到错误:
POST http://localhost:4200/api/posts 404 (Not Found)
帖子最初显示,但没有与帖子关联的用户,然后在页面刷新时消失。
感谢。任何帮助将非常感激。我只是在学习Ember,对于这篇庞大的帖子感到抱歉。