JavaScript 前端 Rails 应用程序中的嵌套属性
我发现 JavaScript 单页应用程序提供的交互性使得在客户端构建复杂的嵌套对象变得非常容易。
例如,在我正在编写的应用程序中,我有一个 Backbone 目的地和起点模型、一条连接它们的路线,以及一辆行驶该路线的公共汽车。所有这些在客户端都很自然地结合在一起。
# Bus toJSON()
{
seats: 45,
route: {
summary: "a route summary",
origin: {
latitude: 45.654634,
longitude: 23.5355
},
destination: {
latitude: 45.654634,
longitude: 23.5355
}
}
}
然而,我发现当需要持久化我的总线时(用户准备好保存所有内容),rails 模型的 accepts_nested_attributes_for
方法使事情变得非常难看。我最终不得不将数据发送到服务器,这看起来像是
{ "bus_route_attributes_origin_attributes_latitude" => "45.654634" }
为了让 ActiveRecord 正常运行。
我应该如何更改我的服务器端以允许我更轻松地处理 JSON?
I find that the interactivity that a JavaScript single-page application provides makes it quite easy to build up complicated nested objects on the client side.
For example, in an application I'm writing, I have a Backbone destination and origin models, a route which connects them and then a bus which travels that route. All of this comes together quite naturally on the client side.
# Bus toJSON()
{
seats: 45,
route: {
summary: "a route summary",
origin: {
latitude: 45.654634,
longitude: 23.5355
},
destination: {
latitude: 45.654634,
longitude: 23.5355
}
}
}
However, I find that when it comes time to persist my bus (the user is ready to save everything), the rails models accepts_nested_attributes_for
method makes things quite ugly. I end up having to send data to the server which looks like
{ "bus_route_attributes_origin_attributes_latitude" => "45.654634" }
in order to get ActiveRecord to play nicely.
How should I change my server side to allow me to deal in JSON more easily?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,当您已经使用accepts_nested_attributes设置模型时,例如更新模型时,您可以简单地在控制器中执行以下操作(我假设您已经执行了类似的操作)
: ,Active Record 只会更新模型中真正发生更改的部分,即使它嵌套在其他模型中。
然而,这种方法需要来自客户端的完整总线对象。如果您只想更新一个属性,那么您将不得不采用目前的方法。我同意这很丑陋,但是当您简单地序列化完整的总线对象并在每次发生变化时将其发送到服务器时,Rails 就会找出为您发生了什么变化。
Well, when you have already setup your models with
accepts_nested_attributes
, then when e.g. updating your model, you can simply do the following in your controller (I assume you already do something like this):With this in place, Active Record will only update those parts of the model that have really changed, even if it's nested within other models.
This approach however expects the full
bus
object from the client. If you only want to update one single attribute, then you are stuck with the approach you have so far. I agree that this is ugly, but when you simply serialize your complete bus object and send it to the server every time something changes, then Rails figures out what changed for you.