骨干要包括created_at,的updated_at等等,但我不希望它 [英] Backbone wants to include created_at, updated_at, etc., but I don't want it to
问题描述
我使用的骨干和Rails。我有我可以创建和销毁就好了一个模型。当我编辑,不过,我得到这个错误:
I'm using Backbone with Rails. I have a model that I can create and destroy just fine. When I edit, though, I get this error:
Can't mass-assign protected attributes: created_at, id, updated_at
这是有道理的。这些属性被保护,它们应该受到保护。骨干不应试图更新这些属性,但骨干不知道更好。
That makes sense. Those attributes are protected and they should be protected. Backbone shouldn't be trying to update these attributes, but Backbone doesn't know better.
一个选择,当然是删除 PARAMS [:created_at]
等在我的Rails的控制器,但我可以想像,变得非常UN-DRY pretty快,再加上它只是似乎是错误的不得不这样做。
One option, of course, would be to remove params[:created_at]
, etc. in my Rails controller, but I can imagine that getting really un-DRY pretty quick, and plus it just seems wrong to have to do that.
有没有办法让我告诉骨干不要在其形式包括这些属性?
Is there a way for me to tell Backbone not to include these attributes in its forms?
推荐答案
要么不将它们发送到客户端,以便您的骨干机型从不知道它们或覆盖的 的toJSON
在你的模型将它们排除在外。
Either don't send them to the client so that your Backbone model never knows about them or override toJSON
in your model to exclude them.
默认的toJSON
的实施是很简单的:
The default toJSON
implementation is very simple:
toJSON: function() {
return _.clone(this.attributes);
}
所以你可以用这个替代它:
so you can replace it with this:
toJSON: function() {
var attrs = _(this.attributes).clone();
delete attrs.created_at;
delete attrs.updated_at;
return attrs;
}
您甚至可以猴子补丁右转入 Backbone.Model.prototype
如果这是有道理的你。
You could even monkey patch that right into Backbone.Model.prototype
if that made sense to you.
改变的缺点的toJSON
是的toJSON
趋于完成双重任务的骨干:
The downside of altering toJSON
is that toJSON
tends to do double duty in Backbone:
-
的toJSON
用来序列模型和集合服务器。 -
的toJSON
用来序列模型和收藏的看法。
toJSON
is used to serialize models and collections for the server.toJSON
is used to serialize models and collections for views.
如果您仍然想使用的updated_at
和 created_at
的意见,那么我建议添加另一种方法,说 serialize_for_view
,那做什么标准的的toJSON
所做的:
If you still want to use updated_at
and created_at
in views then I'd recommend adding another method, say serialize_for_view
, that does what the standard toJSON
does:
serialize_for_view: function() {
return _(this.attributes).clone();
}
然后使用类似 VAR HTML = this.template东西({L:this.model.serialize_for_view()})
来建立你的视图的HTML。你也可以猴补丁 serialize_for_view
到 Backbone.Model.prototype
如果你想在任何地方使用它。
and then use things like var html = this.template({m: this.model.serialize_for_view()})
to build your view's HTML. You could also monkey patch serialize_for_view
into Backbone.Model.prototype
if you wanted to use it everywhere.
这篇关于骨干要包括created_at,的updated_at等等,但我不希望它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!