如何通过JSON将多个对象传递给Rails控制器操作“create”?

时间:2013-12-03 00:50:10

标签: ruby-on-rails json knockout.js

正如你可以通过这个问题所说,我是Ruby on Rails和Knockout的新手。

我正在尝试构建一个RoR Web应用程序,允许用户提取存储在MySQL数据库中的资产数据,使用前端的Knockout编辑该数据,然后使用Knockout发送修订版本数据通过Ajax to Rails返回服务器。

点击此处的网址:http://knockoutjs.com/documentation/observableArrays.html 它说:

The convention in Rails is that, when you pass into an action a JSON object 
graph, the framework can automatically convert it to an ActiveRecord object 
graph and then save it to your database. It knows which of the objects are 
already in your database, and issues the correct INSERT or UPDATE statements.

我尝试过进行谷歌搜索,但我没有找到任何能让我这样的新手明白的东西。所以我在这里问这个问题。

在Knockout.js中,当用户提交时,他们将触发一个函数“saveAssets”,它将以JSON格式将数据发送到Rails应用程序上的“/ assets”。我们的想法是“self.assets()”将包含Asset对象的多个实例。

self.saveAssets = function() {
    $.ajax('/assets', {
        data: ko.toJSON({ assets: self.assets() }),
        type: "post",
        contentType: "application/json",
        success: function() { console.log('hella') }
    });
};

当该函数执行时,这里是发布到Rails服务器的JSON。大多数Asset对象都有id值,这意味着它们已经在服务器中,我只想更新它们,但是还有一个没有id号的新资产记录:

{"assets": [
  {"id":1,"desc":"DWS Investments Roth IRA Mutual Fund","shares":"810.577","symbol":"SCQGX","price":"41.17","total":"33371.46"},
  {"id":2,"desc":"DWS Investments Money Market Fund","shares":"20000.00","symbol":null,"price":1,"total":"20000.00"},
  {"id":6,"desc":"credit card debt","shares":"-8700.00","symbol":null,"price":1,"total":"-8700.00","_destroy":true},
  {"shares":"0.00","symbol":"","price":1,"total":"0.00"}
]}

这是Ruby on Rails控制器操作代码:

def create  
  respond_to do |format|
    format.json {
      @assets = params[:assets]
      @assets.each do |this_asset|
        @a = Asset.new(this_asset)
        @a.save
      end
    }
  end
end

我应该在“创建”操作中做什么才能接收JSON数组,将其解析为单独的“Asset”对象并将其保存/更新到数据库?

感谢您的帮助!

0 个答案:

没有答案