2016-07-30 102 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