简体   繁体   English

将对象数组从 JS 传递到 rails controller 以进行创建

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

I am trying to pass an array of objects from my JS to my Rails controller so that I can loop through the array and check to see if each object exists, and if not, create it.我正在尝试将一组对象从我的 JS 传递到我的 Rails controller 以便我可以遍历该数组并检查每个 object 是否存在,如果不存在,则创建它。 I'm having a difficult time getting my strong params setup properly.我很难正确设置强大的参数。 Seems like no matter what I do, I'm getting some kind of an error about unpermitted params.似乎无论我做什么,我都会收到关于未经许可的参数的某种错误。

My JS that is creating and sending the data:我正在创建和发送数据的 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);
    }
  });

My rails controller我的导轨 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

Right now if I run this the server log shows现在如果我运行这个服务器日志显示

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)

Thanks in advance for any advice!提前感谢您的任何建议!

Try this尝试这个

$.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