Leahcim
Leahcim

Reputation: 41919

Syntax for serializing data in rails

According to the Rails docs http://api.rubyonrails.org/classes/ActiveRecord/Base.html, I can store an array in a database using the serialize method

 class User < ActiveRecord::Base
      serialize :preferences, Hash
    end

    user = User.create(:preferences => %w( one two three ))

In my dinky application, I seralized the answers column of the Question model, because there will be multiple possible answer choices

class Question < ActiveRecord::Base
  attr_accessible :question, :link, :answers, :correctanswers

  serialize :answers

end

Trying to seed the database to test it, I did this...

Question.create!( question: "what is R's favorite color", answers: "a" => %w( red green blue ), correctanswer: "blue", link => "http://janesblog.com")

However, the rake db.seed aborted with all sorts of errors suggesting I have the syntax wrong

/Users/mm/Sites/ljk/db/seeds.rb:17: syntax error, unexpected tASSOC, expecting ')'
...avorite color", answers: "a" => %w( red green blue ), correc...
...                               ^
/Users/mm/Sites/ljk/db/seeds.rb:17: syntax error, unexpected ',', expecting $end
...s: "a" => %w( red green blue ), correctanswer: "blue", link ...

Can anyone assist with the correct syntax? Table

class CreateQuestions < ActiveRecord::Migration
  def change
    create_table :questions do |t|

      t.string :question
      t.string :link
      t.text   :answers
      t.string :correctanswer


      t.timestamps
    end
  end
end

Upvotes: 0

Views: 318

Answers (2)

Adam Tanner
Adam Tanner

Reputation: 917

I think you want:

Question.create!(
  question: "what is R's favorite color",
  answers: %w( red green blue ),
  correctanswer: "blue",
  link: "http://janesblog.com"
)

Upvotes: 0

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

This isn't valid ruby:

answers: "a" => %w( red green blue )

You can do this:

answers: { "a" => %w( red green blue ) }

Upvotes: 1

Related Questions