1

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!

1
  • In your Category model, define attr_accessor :categories. So, that the parameter categories can be act as a reader + writer (getter + setter) at a time without defining it in the schema. Commented Sep 20, 2019 at 2:27

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

You might want to point out why that might work. Specifically, how categories in the params is currently a JSON string. And how you're dropping stringify so that it is received in params as a proper array
This was what I need. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.