如何防止Ember Data保存属性(即只读属性) [英] How to prevent Ember Data from saving attribute (ie., Read-only attribute)
问题描述
在发布表单,用户必须能够将一段代码剪切/粘贴到他/她的网页中,才能以ajax的形式配置。
因此,Form模型的embed-snippet属性应该是只读的。当用户更改表单并重新保存记录时,我不希望将代码段的内容发送回服务器。
某些方法我已经考虑过:
- 修改序列化程序以检查此特定属性,并将其从有效载荷中删除,然后再发送到后端
- 将embed-snippet字段转换为与Form模型关系的单独模型,然后从save
- 中创建一个新的Ember Data属性类型
理想情况下,会有一个更好的方法来处理这个问题。
如下:
'DS.attr('string',{readOnly:true})
所以我的问题是,什么是确保此字段的内容不会被发回的最佳方法到服务器?
要获取 (在$ code> serializers / application.js {readOnly:true} code>功能(这样可以更容易地添加新的模型/ attrs),您可以在
): JSONAPISerializer上定制
serializeAttribute
方法
从ember-data导入DS;
导出默认DS.JSONAPISerializer.extend({
serializeAttribute(snapshot,json,key,attribute){
//不序列化属性!
if( attribute.options&& attribute.options.readOnly){
return;
}
this._super(... arguments);
},
} );
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.
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.
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.
Some approaches I have considered:
- Modifying the serializer to check for this specific attribute and drop it from the payload before sending it to the back-end
- Converting the 'embed-snippet' field to a separate model with a relationship to the Form model, and then excluding it somehow from the save
- Creating a new Ember Data attribute type
Ideally there would be a better way to deal with this problem.
Something like:
'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?
To get the { readOnly: true }
functionality (which makes it easier to add new models/attrs) you can customize the serializeAttribute
method on the JSONAPISerializer
:
(in 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屋!