简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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