我想製作一個配方網站,當我嘗試執行一個curl請求以將數據作爲數組保存到我的數據庫時遇到一些問題。我爲我的後端使用了rails,而我的數據庫使用了psql。無法通過導軌將數組保存到數據庫中
遷移
class CreateRecipes < ActiveRecord::Migration
def change
create_table :recipes do |t|
t.text :instruction, array: true, default: []
end
end
end
模型
class Recipe < ActiveRecord::Base
serialize :instruction,Array
end
控制器
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 --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"]
}
}'
後,我用撬測試,
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"]}
所以任何人都可以讓我知道了什麼問題?以及如何解決它?謝謝。
你面臨的問題是什麼? –