0

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

2 Answers 2

1

This isn't valid ruby:

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

You can do this:

answers: { "a" => %w( red green blue ) }
Sign up to request clarification or add additional context in comments.

1 Comment

wait, all I want is an array of colors in the answers column of the database. That "a" probably doesn't/shouldn't be there. Would you mind showing me how to do it that way? Thanks so much.
0

I think you want:

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

2 Comments

that gives me a wrong number of arguments error: wrong number of arguments (1 for 2)
but the records are in the database nevertheless. Thanks

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.