如何防止 Ember Data 保存属性(即只读属性) [英] How to prevent Ember Data from saving attribute (ie., Read-only attribute)

查看:14
本文介绍了如何防止 Ember Data 保存属性(即只读属性)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 json_api_resources gem 在前端使用 Ember 2.0 和后端使用 Rails 4.2 创建在线表单构建器.

I am creating an online form builder using Ember 2.0 on the front-end and Rails 4.2 on the back-end with the json_api_resources gem.

在发布表单的过程中,用户必须能够将一段代码剪切/粘贴到他/她的网页中,以便在他们配置的表单中使用ajax".

In the process of publishing a form, a user must be able to cut/paste a snippet of code into his/her webpage in order to 'ajax in' the form they have configured.

因此 Form 模型的 'embed-snippet' 属性应该是只读的.当用户更改表单并重新保存记录时,我不希望将代码段字段的内容发送回服务器.

Thus the 'embed-snippet' attribute of the Form model should be read-only. I do not want the contents of the snippet field to be sent back to the server when the user makes a change to the form and re-saves the record.

我考虑过的一些方法:

  • 修改序列化程序以检查此特定属性并将其从有效负载中删除,然后再将其发送到后端
  • 将 'embed-snippet' 字段转换为与 Form 模型有关系的单独模型,然后以某种方式将其从保存中排除
  • 创建新的 Ember 数据属性类型

理想情况下会有更好的方法来处理这个问题.

Ideally there would be a better way to deal with this problem.

类似于:

'DS.attr('string', { readOnly: true })

所以我的问题是,确保该字段的内容不会被发送回服务器的最佳方法是什么?

So my question is, what is the best way to ensure the content of this field does not get sent back to the server?

推荐答案

要获得 { readOnly: true } 功能(可以更轻松地添加新模型/属性),您可以自定义 <JSONAPISerializer 上的 code>serializeAttribute 方法:

To get the { readOnly: true } functionality (which makes it easier to add new models/attrs) you can customize the serializeAttribute method on the JSONAPISerializer:

(在 serializers/application.js 中):

import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({
  serializeAttribute(snapshot, json, key, attribute) {
    // do not serialize the attribute!
    if (attribute.options && attribute.options.readOnly) {
      return;
    }
    this._super(...arguments);
  },
});

这篇关于如何防止 Ember Data 保存属性(即只读属性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆