0

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.

1
  • what is the problem you are facing? Commented Jul 30, 2016 at 16:31

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much~ It solved the problem. But I am having trouble with the nested attributes for child table for my recipe. Would you mind take a look at it? Many thanks for helping. I am a newbie for rails~

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.