tina
tina

Reputation: 35

Can not save array into database by rails

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.

Upvotes: 0

Views: 422

Answers (1)

Nic Nilov
Nic Nilov

Reputation: 5155

Remove serialize :instruction, Array from your Recipe class and it should work.

The reason the instruction attribute doesn't get assigned with serialize is that the latter takes an object and serializes it to YAML. The model's array-typed attribute, in turn, expects a plain ruby array.

serialize facility is for storing arbitrary objects in a text form, usually for subsequent instantiation. It is not necessary to perform serialization for array attributes.

Upvotes: 1

Related Questions