【问题标题】:Save associated record in Ember在 Ember 中保存关联记录
【发布时间】: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


    【解决方案1】:

    创建评论序列化程序并覆盖keyForRelationship 方法,如下所示:

     keyForRelationship(key/*, relationship, method*/) {
         if(key === 'post') return 'post_id';
         return this._super(...arguments);
       }
    

    职位关系应该是:

    post: DS.belongsTo('post')
    

    【讨论】:

    • 谢谢,它成功了。虽然我想知道这是否是正确的方法。我的意思是我没有找到任何包含此类代码的文档或示例。您能否分享一个参考以获得更好的解释。
    • @Aakanksha 我不知道确切的文件,但this。如果后端 API 是 json api 标准,则无需更改,JSONAPISerializer 就足够了。但正如您所描述的,您在 rest api 和序列化中的后端可能会因情况而异。例如对我来说,所有的关系都是骆驼式的。 Ember 让您自定义您想要的每个部分。 AFAIK,这是解决您问题的最佳方法。最佳
    • 这是有道理的。我一定为此错过了 Ember Doc。非常感谢您的参考。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多