I am trying to make a recipe website and I got some problems when I try to do a curl request to save my data as an array into my database. I used rails for my backend, and psql for my database.
Migration
class CreateRecipes < ActiveRecord::Migration
def change
create_table :recipes do |t|
t.text :instruction, array: true, default: []
end
end
end
Model
class Recipe < ActiveRecord::Base
serialize :instruction,Array
end
Controller
def create
@recipe = Recipe.new(recipe_params)
**_binding.pry_**
current_user.recipes << @recipe
if @recipe.save
render json: @recipe, status: :created, location: @recipe
else
render json: @recipe.errors, status: :unprocessable_entity
end
end
def recipe_params
params.require(:recipes)
.permit(:name, :category, instruction: [])
end
Curl request
curl --include --request POST http://localhost:3000/recipes \
--header "Authorization: Token token=........" \
--header "Content-Type: application/json" \
--data '{
"recipes": {
"name": "an example recipe",
"category": "fry",
"instruction": ["do it", "ignore it"]
}
}'
After I test with pry,
pry(#<RecipesController>)> @recipe
=> #<Recipe:0x007fa0aeafa770 id: nil, name: "an example recipe", category: "fry", instruction: [], user_id: nil, created_at: nil, updated_at: nil>`
pry(#<RecipesController>)> recipe_params
=> {"name"=>"an example recipe", "category"=>"fry", "instruction"=>["do it", "ignore it"]}
So could anyone let me know what's the problem? And how to fix it? Thank you.