如何格式化to_json输出以适应update_attributes

时间:2014-09-01 06:27:58

标签: ruby-on-rails json angularjs activerecord ruby-on-rails-4

我正在开发Angular JS + Rails项目。我在JSON下面传递给由to_json

创建的angularJS

user_controller.rb

render :json => current_user.to_json(:include => [:projects,:courses,:awards]) 

用户控制器输出

{"_json"=>   
   [{"id"=>21,
    "name"=>"Demo Name",
    "email"=>"demo@demo.com",
    "mobile"=>"",
    "dob"=>nil,
    "gender"=>nil,
    "address"=>nil,
    "intro"=>nil,
    "created_at"=>"2014-09-01T05:29:38.000Z",
    "updated_at"=>"2014-09-01T05:29:38.000Z",
    "projects"=>[{"id":1,"name":"Existing Project"}],
    "courses"=>[],
    "awards"=>[]
   }] 
}

Assigning data to angular $scope.userData = response._json

在Angular View中,使用HTML5 contenteditable(angular Directive),我正在改变上述对象的值。

角度视图

<h3 ng-model="userData[0].name" contenteditable="true"></h3>

内容正在按预期变化。

{"_json"=>   
      [{"id"=>21,
        "name"=>"UPDATED NAME HERE",
        "email"=>"demo@demo.com",
        "mobile"=>"",
        "dob"=>nil,
        "gender"=>nil,
        "address"=>nil,
        "intro"=>nil,
        "created_at"=>"2014-09-01T05:29:38.000Z",
        "updated_at"=>"2014-09-01T05:29:38.000Z",
        "projects"=>[{"id":1, "name":"Existing Project"},{"name":"ADDED NEW PROJECT HERE"}],
        "courses"=>[{"name":"ADDED NEW COURSE HERE"}],
        "awards"=>[]
       }] 
    }

现在我需要将此对象发布到服务器并更新用户数据和所有关联数据,例如具有现有记录和新记录的项目,我需要发布的正确方法和JSON格式,以使此过程简单到可能的。

2 个答案:

答案 0 :(得分:0)

用户角度http帖子。

$http(
   method: 'POST'
   data: your_json_array_here
   url: your_url_to_controller_action

).success((data,status) -> 


).error((data,status) -> 


)

答案 1 :(得分:0)

开始使用Angular Rails Resoures,另一个有用的参考是RestAngular