开发者

Adding an array to a Class (rails)

I'd like to make one of the attributes of my class an array. The class is "Course" and the attribute is Course.evals.

I tried using "serialize," ala http://duanesbrain.blogspot.com/2007/04/ruby-on-rails-persist-array-to-database.html, but for some reason it's not working. Here's my relevant code:

class Course < ActiveRecord::Base
  serialize :evals
end

But then when I go into the console, this happens:

ruby-1.开发者_StackOverflow9.2-p290 :043 > blah = Course.find(3)
 => #<Course id: 3, evals: nil> 
ruby-1.9.2-p290 :045 > blah.update_attribute :evals, "thing"
 => true 
ruby-1.9.2-p290 :047 > blah.evals << "thing2"
 => "thingthing2" 
ruby-1.9.2-p290 :048 > blah.save
 => true 
ruby-1.9.2-p290 :050 > blah.evals
 => "thingthing2" 

So blah.evals << "thing2" simply adds "thing2" to the existing "thing" string. It doesn't create a new entry in any array. Does this mean that my program isn't picking up my "serialize" command within the Model? If so, how can I fix it?


I believe the problem is that when you initially assign a value to the attribute, its assigned as a string. If you want to store it as an array you need to initialise the variable as an array...

> blah = Course.find(3)
> blah.update_attribute :evals, ["thing"]

As a side note, you can add an optional param to the serialize method to determine which class the attribute should have when deserializing...

class Course < ActiveRecord::Base
  serialize :evals, Array
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜