Philipp Braun
Philipp Braun

Reputation: 1573

Array in JSON not properly passed to Database

I am trying to create a new entry in my database which contains an array images.

Using Product.new("title":"Hello World", "images":["a.jpg","b.jpg"]) I can create a new entry without problems. But when I try passing the parameters to my API, the array remains empty (all the other fields are filled).

The request I used:

curl -i -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"title":"Hello World",  "images":["a.jpg", "b.jpg"], "api_key":"API_KEY"}' http://localhost:3000/api/products

Parameters are passed using:

def product_params
  params.require(:product).permit(:id, :title, :images)
end

A new database entry is then created using:

Product.new(product_params)

Any help is highly appreciated.

Upvotes: 1

Views: 40

Answers (1)

SoAwesomeMan
SoAwesomeMan

Reputation: 3416

Use images: [].

via: https://stackoverflow.com/a/18641790/1076207

From the documentation [https://github.com/rails/strong_parameters]

The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile.

To declare that the value in params must be an array of permitted scalar values map the key to an empty array:

def product_params
  params.require(:product).permit(:title, images: [])
end

Upvotes: 2

Related Questions