【发布时间】:2017-03-11 06:14:42
【问题描述】:
我是 Ember 的初学者,正在尝试实现一个简单的帖子和评论应用程序。
我有 Rails 背景,因此我为此使用 Rails API。
我已按照教程进行操作,我能够保存帖子、获取其所有 cmets 并删除帖子。但是我在保存与帖子相关的评论时遇到问题。
以下是模型代码
post.js
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
comments: DS.hasMany('comment')
});
comment.js
import DS from 'ember-data';
export default DS.Model.extend({
author: DS.attr('string'),
body: DS.attr('string'),
post: DS.belongsTo('post')
});
routes/post/comment/new.js
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return {};
},
renderTemplate() {
this.render('post.comment.new', { into: 'application' });
},
actions: {
save() {
const post = this.modelFor('post');
const newComment = this.get('store').createRecord('comment', this.currentModel);
newComment.set('post', post);
newComment.save().then(() => {
this.transitionTo('post', post);
});
},
cancel() {
this.transitionTo('post', this.modelFor('post'));
}
}
});
router.js
import Ember from 'ember';
import config from './config/environment';
const Router = Ember.Router.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('posts');
this.route('post.new', { path: 'posts/new' });
this.resource('post', { path: 'posts/:post_id' }, function() {
this.route('comment.new', { path: 'comments/new' });
});
});
export default Router;
保存评论是我面临的问题。这真的很奇怪,但是在保存评论时,传递给服务器的参数看起来像
Parameters: {"comment"=>{"author"=>"dsa", "body"=>"asd", "post"=>"9"}}
Unpermitted parameter: post
据我了解,参数应该是 post_id 而不是 post。如果帖子正在通过,那么它应该是对象。当然我可能是错的,因为我对 Ember 还没有清楚的了解。
在随机摆弄代码时,我发现如果我从
替换 cmets 模型中的关系post: DS.belongsTo('post')
到
post_id: DS.belongsTo('post')
传递给服务器的参数是
Parameters: {"comment"=>{"author"=>"fg", "body"=>"dfs", "post_id"=>nil}}
然而,这实际上并没有将 post_id 作为 nil 传递。
这可能是绝对错误的,而不是它应该如何工作,但我一无所知。
感谢您的帮助。
【问题讨论】:
标签: javascript ruby-on-rails ember.js save has-many