简体   繁体   English

如何将AngularJS json数组发布到Rails后端api?

[英]How to post AngularJS json array to Rails backend api?

I have a list and each list may contain 0 or more items. 我有一个列表,每个列表可能包含0个或多个项目。 I'm new to Angularjs and I'm using angularJS $resource to to POST to my rails backend API for creating this list with items. 我是Angularjs的新手,我正在使用angularJS $ resource张贴到我的rails后端API,以使用项目创建此列表。 If I create a test array like below and use ListItem.save $scope.test then this POST completes successfully to my Rails backend api. 如果我创建如下所示的测试数组并使用ListItem.save $scope.test则此POST成功完成到我的Rails后端api。

$scope.test = 'item_id': '55' 'qty': '6' 'uom': 'each'

Processing by Api::V1::ListItemsController#create as JSON 由Api :: V1 :: ListItemsController#create作为JSON处理

Parameters: {"item_id"=>"55", "qty"=>"6", "uom"=>"each", "list_id"=>"14", "list_item"=>{"item_id"=>"55", "qty"=>"6", "uom"=>"each"}} List Load (0.1ms) SELECT "lists".* FROM "lists" WHERE "lists"."id" = ? 参数:{“ item_id” =>“ 55”,“ qty” =>“ 6”,“ uom” =>“ each”,“ list_id” =>“ 14”,“ list_item” => {“ item_id” => “ 55”,“ qty” =>“ 6”,“ uom” =>“每个”}}}列表加载(0.1ms)选择“ lists”。*从“ lists”中“ lists”。“ id” =? LIMIT 1 [["id", 14]] (0.1ms) begin transaction SQL (0.3ms) INSERT INTO "list_items" ("item_id", "qty", "uom", "list_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?) [["item_id", 55], ["qty", 6], ["uom", "each"], ["list_id", 14], ["created_at", "2015-06-06 06:14:12.844167"], ["updated_at", "2015-06-06 06:14:12.844167"]] (2.0ms) commit transaction Completed 200 OK in 7ms (Views: 0.5ms | ActiveRecord: 2.6ms) woohoo!!! LIMIT 1 [[“ id”,14]](0.1ms)开始事务SQ​​L(0.3ms)插入“ list_items”(“ item_id”,“ qty”,“ uom”,“ list_id”,“ created_at”,“ updated_at “)值(?,?,?,?,?,?)[[” item_id“,55],[” qty“,6],[” uom“,” each“],[” list_id“,14] ,[“ created_at”,“ 2015-06-06 06:14:12.844167”],[“ updated_at”,“ 2015-06-06 06:14:12.844167”]](2.0ms)提交事务在7ms内完成200 OK (观看次数:0.5ms | ActiveRecord:2.6ms) woohoo!!!

However things quickly fall apart when I create a json array in my controller and try to save this array. 但是,当我在控制器中创建一个json数组并尝试保存该数组时,事情很快就会崩溃。 Then this does not complete successfully (error below) 然后这不会成功完成(以下错误)

[ { "item_id": 32, "qty": "1", "uom": "Dozen" } ]

Processing by Api::V1::ListItemsController#create as JSON 由Api :: V1 :: ListItemsController#create作为JSON处理

Parameters: {"_json"=>[{"item_id"=>34, "qty"=>"1", "uom"=>"Each"}], "list_id"=>"14", "list_item"=>{}} List Load (0.1ms) SELECT "lists".* FROM "lists" WHERE "lists"."id" = ? 参数:{“ _json” => [{“ item_id” => 34,“ qty” =>“ 1”,“ uom” =>“每个”}]],“ list_id” =>“ 14”,“ list_item” = > {}}列表加载(0.1毫秒),选择“列表”。*从“列表”,在“列表”中。“ id” =? LIMIT 1 [["id", 14]] Completed 400 Bad Request in 2ms ActionController::ParameterMissing (param is missing or the value is empty: list_item): app/controllers/api/v1/list_items_controller.rb:50:in listItem_params' app/controllers/api/v1/list_items_controller.rb:21:in create' LIMIT 1 [[“ id”,14]]在2毫秒内完成了400错误请求ActionController :: ParameterMissing(参数缺失或值为空:list_item):app / controllers / api / v1 / list_items_controller.rb:50:in listItem_params' app/controllers/api/v1/list_items_controller.rb:21:in create'

I even tried to add the list_item object to the json array using ListItem.save {list_item: $scope.final} and then a different error is received below. 我什至尝试使用ListItem.save {list_item: $scope.final}将list_item对象添加到json数组,然后在下面收到另一个错误。

Processing by Api::V1::ListItemsController#create as JSON 由Api :: V1 :: ListItemsController#create作为JSON处理

Parameters: {"list_item"=>[{"item_id"=>30, "qty"=>"1", "uom"=>"Each"}], "list_id"=>"14"} List Load (0.1ms) SELECT "lists".* FROM "lists" WHERE "lists"."id" = ? 参数:{“ list_item” => [{“ item_id” => 30,“ qty” =>“ 1”,“ uom” =>“ Each”}],“ list_id” =>“ 14”}列表加载(0.1 ms)选择“列表”。*从“列表”中选择“列表”。“ id” =? LIMIT 1 [["id", 14]] Completed 500 Internal Server Error in 2ms NoMethodError (undefined method permit' for [{"item_id"=>30, "qty"=>"1", "uom"=>"Each"}]:Array): app/controllers/api/v1/list_items_controller.rb:50:in listItem_params' app/controllers/api/v1/list_items_controller.rb:21:in `create' LIMIT 1 [[“ id”,14]]在2毫秒内完成了500个内部服务器错误NoMethodError( permit' for [{"item_id"=>30, "qty"=>"1", "uom"=>"Each"}]:Array): app/controllers/api/v1/list_items_controller.rb:50:in listItem_params'app / controllers / api / v1 / list_items_controller.rb:21:in'create'

list_items_controller list_items_controller

    module Api
  module V1
class ListItemsController < ApplicationController
  protect_from_forgery
  skip_before_action :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }
  before_action :set_list
  respond_to :json

  def index
    respond_with ListItem.all
  end

  def new
  end

  def create
    @li = @list.list_items.new(listItem_params)
      if @li.save
        render :status => 200,
           :json => { :success => true,
                      :info => "ItemAdded",
                      :data => { :item => @li }}
      else
        render :status => :unprocessable_entity,
           :json => { :success => false,
                      :info => resource.errors,
                      :data => {} }                              
      end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_list
      @list = List.find(params[:list_id])
    end

    def listItem_params
      params.require(:list_item).permit(:list_id, :item_id, :qty, :uom)
           end
      protected

        def json_request?
          request.format.json?
        end
    end
  end
end

lists.coffee (relevant sections) 清单。咖啡(相关章节)

    app = angular.module('myApp', [ 'ngResource' ])

ListItem = app.factory('ListItem', ($resource) ->

  $resource '/api/v1/lists/14/list_items/:id', { id: '@id' }, update: method: 'PUT'
)
app.controller 'myCtrl', ($scope, ListItem) ->
  $scope.selection = []
  $scope.final = []
  $scope.test =
  'item_id': '55'
  'qty': '6'
  'uom': 'each'

  $scope.saveListItems = ()->
    i = 0
    while i < $scope.selection.length
      obj = $scope.selection[i]
      $scope.final.push 
        'item_id': obj.id
        'qty': obj.qty
        'uom': obj.uom
      li= ""
      li = ListItem.save $scope.final
      i++

selection array will contain the following for example when I add an item to the selection. 例如,当我将一个项目添加到选择中时,选择数组将包含以下内容。

[
  {
    "id": 32,
    "name": "Eggs",
    "created_at": "2015-04-29T00:14:19.627Z",
    "updated_at": "2015-04-29T00:14:19.627Z",
    "user_id": null,
    "qty": "1",
    "uom": "Dozen"
  }
 ]

And when I click the confirm button then the saveListItems function is executed 当我单击确认按钮时,将执行saveListItems函数

<button class="btn btn-lg btn-primary" ng-click="saveListItems()">Confirm</button>

the final array contains the following after the saveListItems function is run: 运行saveListItems函数后,最终数组包含以下内容:

[
  {
    "item_id": 32,
    "qty": "1",
    "uom": "Dozen"
  }
]

I would like to have angularjs build the array correctly so that it will POST a new list item successfully to my rails backend api. 我想让angularjs正确构建数组,以便它将新列表项成功发布到我的rails后端api。 Any suggestions on how to fix this? 对于如何解决这个问题,有任何的建议吗?

I found a similar SO question here How do I save an Angular form to my ruby on rails backend? 我在这里发现了一个类似的SO问题, 如何在rails后端将Angular表单保存到我的红宝石中?

And instead of using $resource I used $http in the saveListItems function as shown below: 而不是使用$ resource,我在saveListItems函数中使用了$ http,如下所示:

  $scope.saveListItems = ->
    i = 0
    while i < $scope.selection.length
      obj = $scope.selection[i]
      $scope.final = 'list_item':
        'item_id': obj.id
        'qty': obj.qty
        'uom': obj.uom
      $http
        method: 'POST'
        url: 'http://192.168.0.6:3000/api/v1/lists/14/list_items'
        data: $scope.final
      return
      i++

Next, I included the $http service in the controller like this: 接下来,我将$ http服务包含在控制器中,如下所示:

app.controller 'myCtrl', ($scope, ListItem, $http) ->

Retested and it worked! 重新测试,它的工作!

Processing by Api::V1::ListItemsController#create as JSON 由Api :: V1 :: ListItemsController#create作为JSON处理

Parameters: {"list_item"=>{"item_id"=>56, "qty"=>"2", "uom"=>"Dozen"}, "list_id"=>"14"} List Load (0.2ms) SELECT "lists".* FROM "lists" WHERE "lists"."id" = ? 参数:{“ list_item” => {“ item_id” => 56,“ qty” =>“ 2”,“ uom” =>“十二”},“ list_id” =>“ 14”}列表加载(0.2ms)选择“列表”。*从“列表”中选择“列表”。“ id” =? LIMIT 1 [["id", 14]] (0.1ms) begin transaction SQL (0.4ms) INSERT INTO "list_items" ("item_id", "qty", "uom", "list_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?) [["item_id", 56], ["qty", 2], ["uom", "Dozen"], ["list_id", 14], ["created_at", "2015-06-06 23:50:30.564950"], ["updated_at", "2015-06-06 23:50:30.564950"]] (1.8ms) commit transaction Completed 200 OK in 6ms (Views: 0.4ms | ActiveRecord: 2.3ms) waahoo!! LIMIT 1 [[“ id”,14]](0.1ms)开始事务SQ​​L(0.4ms)插入“ list_items”(“ item_id”,“ qty”,“ uom”,“ list_id”,“ created_at”,“ updated_at “)值(?,?,?,?,?,?)[[” item_id“,56],[” qty“,2],[” uom“,”十二“],[” list_id“,14] ,[“ created_at”,“ 2015-06-06 23:50:30.564950”],[“ updated_at”,“ 2015-06-06 23:50:30.564950”]](1.8ms)提交事务在6ms内完成200 OK (观看次数:0.4ms | ActiveRecord: waahoo!!waahoo!!

I then re-tested with $resource but changed the saveListItems function as shown below: 然后,我使用$ resource重新测试,但更改了saveListItems函数,如下所示:

  $scope.saveListItems = ->
    i = 0
    while i < $scope.selection.length
      obj = $scope.selection[i]
      $scope.final = 'list_item':
        'item_id': obj.id
        'qty': obj.qty
        'uom': obj.uom
      ListItem.save($scope.final)
      i++


    return

And next, I removed the $http service from the controller 接下来,我从控制器中删除了$ http服务

app.controller 'myCtrl', ($scope, ListItem) ->

This also worked!! 这也有效!

Processing by Api::V1::ListItemsController#create as JSON 由Api :: V1 :: ListItemsController#create作为JSON处理

Parameters: {"list_item"=>{"item_id"=>60, "qty"=>"4", "uom"=>"Each"}, "list_id"=>"14"} List Load (0.2ms) SELECT "lists".* FROM "lists" WHERE "lists"."id" = ? 参数:{“ list_item” => {“ item_id” => 60,“ qty” =>“ 4”,“ uom” =>“每个”},“ list_id” =>“ 14”}列表加载(0.2ms)选择“列表”。*从“列表”中选择“列表”。“ id” =? LIMIT 1 [["id", 14]] (0.1ms) begin transaction SQL (0.4ms) INSERT INTO "list_items" ("item_id", "qty", "uom", "list_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?) [["item_id", 60], ["qty", 4], ["uom", "Each"], ["list_id", 14], ["created_at", "2015-06-07 00:27:12.125078"], ["updated_at", "2015-06-07 00:27:12.125078"]] (2.2ms) commit transaction Completed 200 OK in 8ms (Views: 0.5ms | ActiveRecord: 2.8ms) LIMIT 1 [[“ id”,14]](0.1ms)开始事务SQ​​L(0.4ms)插入“ list_items”(“ item_id”,“ qty”,“ uom”,“ list_id”,“ created_at”,“ updated_at “)值(?,?,?,?,?,?)[[” item_id“,60],[” qty“,4],[” uom“,”每个“],[” list_id“,14] ,[“ created_at”,“ 2015-06-07 00:27:12.125078”],[“ updated_at”,“ 2015-06-07 00:27:12.125078”]](2.2ms)提交事务在8ms内完成200 OK (观看次数:0.5ms | ActiveRecord:2.8ms)

Hope this info helps others. 希望此信息对其他人有帮助。 I'm sure this code can use some serious refactoring though as I'm still learning Angularjs so that's my disclaimer : ) 我确信这段代码可以使用一些严肃的重构,尽管我仍在学习Angularjs,所以这是我的免责声明:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM