簡體   English   中英

將對象數組從 JS 傳遞到 rails controller 以進行創建

[英]Pass array of objects from JS to rails controller for creation

我正在嘗試將一組對象從我的 JS 傳遞到我的 Rails controller 以便我可以遍歷該數組並檢查每個 object 是否存在,如果不存在,則創建它。 我很難正確設置強大的參數。 似乎無論我做什么,我都會收到關於未經許可的參數的某種錯誤。

我正在創建和發送數據的 JS:

function addGame(gameData) {
  var parser = new DOMParser();
  var xmlDoc = parser.parseFromString(gameData,"text/xml");

  // Check categories and create any new categories that need created
  var gameCategories = [];

  // for each category in the JSON push into gameCategories  
  var x = xmlDoc.getElementsByTagName("link").length;
  var i = 0
  for (i = 0; i < x ; i++) { 
    var type = xmlDoc.getElementsByTagName("link")[i].getAttribute("type");
    if (type == "boardgamecategory") {
      var categoryData = {
        name: xmlDoc.getElementsByTagName("link")[i].getAttribute("value"),
        bgg_id: xmlDoc.getElementsByTagName("link")[i].getAttribute("id")
      };
      gameCategories.push(categoryData);
    }
  }

  console.log(gameCategories);

  // Try sending all of the categories at once

  $.ajaxSetup({
    headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
  });

  $.ajax({
    url: '/categories',
    type: 'POST',
    dataType: 'json',
    data: { categories: JSON.stringify(gameCategories)},
    success: function (response) {
      console.log(response);
    }
  });

我的導軌 controller

class CategoriesController < ApplicationController

  def create

    logger.debug category_params
    # @category = Category.find_or_initialize_by(category_params)
    # if @category.save
    #   logger.debug "Category Saved"
    # else
    #   flash[:danger] = "There was a problem creating one of the game categories ¯\_(ツ)_/¯"
    #   redirect_to root_url
    # end
  end

  private

    def category_params
      params.permit(categories: [])
    end
end

現在如果我運行這個服務器日志顯示

Started POST "/categories" for ::1 at 2019-09-19 21:45:33 -0400
Processing by CategoriesController#create as JSON
  Parameters: {"categories"=>"[{\"name\":\"Adventure\",\"bgg_id\":\"1022\"},{\"name\":\"Exploration\",\"bgg_id\":\"1020\"},{\"name\":\"Fantasy\",\"bgg_id\":\"1010\"},{\"name\":\"Fighting\",\"bgg_id\":\"1046\"},{\"name\":\"Miniatures\",\"bgg_id\":\"1047\"}]"}
  User Load (0.5ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
  ↳ app/helpers/sessions_helper.rb:18
Unpermitted parameter: :categories
{}
No template found for CategoriesController#create, rendering head :no_content
Completed 204 No Content in 95ms (ActiveRecord: 22.8ms)

提前感謝您的任何建議!

嘗試這個

$.ajax({
    url: '/categories',
    type: 'POST',
    dataType: 'json',
    data: { categories: gameCategories},
    success: function (response) {
      console.log(response);
    }
  });
def category_params
  params.permit(categories: [:name, :bgg_id])
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM