根据 Rails 文档http://api.rubyonrails.org/classes/ActiveRecord/Base.html,我可以使用 serialize 方法将数组存储在数据库中
class User < ActiveRecord::Base
serialize :preferences, Hash
end
user = User.create(:preferences => %w( one two three ))
在我极小的应用程序中,我对 Question 模型的 answers 列进行了序列化,因为会有多种可能的答案选择
class Question < ActiveRecord::Base
attr_accessible :question, :link, :answers, :correctanswers
serialize :answers
end
试图为数据库播种以对其进行测试,我这样做了...
Question.create!( question: "what is R's favorite color", answers: "a" => %w( red green blue ), correctanswer: "blue", link => "http://janesblog.com")
但是,rake db.seed 因各种错误而中止,表明我的语法错误
/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 ...
任何人都可以帮助使用正确的语法吗?桌子
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