2016-07-30 7 views
0

レシピのウェブサイトを作成しようとしていて、データを配列としてデータベースに保存するためにカール要求を行うといくつかの問題が発生します。バックエンドにはレールを、データベースには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

Recipeクラスからserialize :instruction, Arrayを削除するとうまくいくはずです。

instruction属性がserializeで割り当てられない理由は、後者がオブジェクトを受け取り、それをYAMLにシリアル化するからです。モデルの配列型の属性には、純粋なルビ配列が必要です。

serializeファシリティは、任意のオブジェクトをテキスト形式で格納するためのもので、通常後続のインスタンス化のために使用されます。配列の属性をシリアライズする必要はありません。

+0

ありがとうございました〜問題を解決しました。しかし、レシピの子テーブルのネストされた属性に問題があります。あなたはそれを見てみましょうか?助けてくれてありがとう。私はレールの初心者です〜 – tina

関連する問題