2016-07-30 99 views
0

我想製作一個配方網站,當我嘗試執行一個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"]} 

所以任何人都可以讓我知道了什麼問題?以及如何解決它?謝謝。

+0

你面臨的問題是什麼? –

回答

1

刪除serialize :instruction, Array從你的Recipe類,它應該工作。

instruction屬性未分配到serialize的原因是後者需要一個對象並將其序列化爲YAML。該模型的數組類型屬性反過來期望一個普通的紅寶石數組。

serialize設施用於以文本形式存儲任意對象,通常用於後續實例化。不需要爲數組屬性執行序列化。

+0

非常感謝你解決了這個問題。但是我的配方的子表的嵌套屬性有問題。你介意看看嗎?非常感謝您的幫助。我是一個新手爲rails〜 – tina