如何过滤掉 Backbone 中不应包含在 POST 请求中的属性?
我有一个带有backbone-rails gem 的Rails 应用程序。效果很好,但 Backbone 尝试发送包含模型所有属性的请求。有没有办法可以过滤掉一些将在更新/新内容上发布的属性?这对于那些虚拟属性和无法批量分配的属性非常有用。
I have a Rails application with the backbone-rails gem. Which works out fine but Backbone tries to send a request with all the attributes of the model. Is there a way I can filter out some of the attributes that will be POST'd on an update/new? This would work great for those virtual attributes and attributes that can't be mass assigned.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发布不能批量分配的属性并没有什么坏处。您会看到一条警告,但一切都会正常。
基本上有两种方法可以实际删除不需要的属性。第一个是自定义模型的
toJSON()
。例如:第二种不太干净的方法是显式地将调用中的数据传递给
Model.save()
。如果您使用默认的 Backbone.sync() 方法,则将使用此数据。例如:您可能可以找出一种方法来概括这两种方法中的任何一种,具体取决于哪种方法适合您。
There is no harm in posting attributes that cannot be mass assigned. You will see a warning, but everything will work.
There are basically two ways of actually removing unwanted attributes. The first is to customize the Model's
toJSON()
. For example:The second, and less clean way, is to explicitly pass the data in your call to
Model.save()
. If you are using the defaultBackbone.sync()
method, then this data will be used instead. For example:You can probably figure out a way to generalize either of those approaches, depending on which one works for you.