2011-05-13 66 views
1

我想将数组存储到数据库字段中。 我尝试以下方法:将数组导入数据库字段

class MyStuff < ActiveRecord::Base 
    serialize :things 
end 

stuff = MyStuff.new 
stuff.things << "pen" 
stuff.things << "paper" 
stuff.save 

我得到一个错误:“发生错误,而评估为零< <。”

有没有其他办法?

回答

8

什么是“事物”。将它定义为Array或Hash或者你想要的东西,然后向它添加元素。

stuff = MyStuff.new 

stuff.things = [] 
stuff.things << "pen" 
.. 

stuff.save 
+0

非常感谢.... – lamrin 2011-05-13 14:27:59

2

你可以使用它,这也适用于现有的东西。

stuff.things ||= [] //without || your existing things will be reset 
stuff.things << "pen" 
.. 
+1

好一点。使用'.new'并不重要,但是对于现有的记录,您的答案会节省很多删除他们的数据! – mjnissim 2012-08-10 18:58:08