Back

在Rails3中,保存任意结构的对象到 数据库 (save schema-less object to Rails DB's string column )

发布时间: 2013-01-29 02:48:00

Saving arrays, hashes, and other non-mappable objects in text columns

AR 可以保存任意对象到 TEXT 列。如下:   ( Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method serialize. This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work. ) 

class User < ActiveRecord
::
Base
  serialize :preferences
end

user = User.create(:preferences => { "background" => "black", "display" => large })
User.find(user.id).preferences # => { "background" => "black", "display" => large }

也可以指定该对象的类型( You can also specify a class option as the second parameter that’ll raise an exception if a serialized object is retrieved as a descendant of a class not in the hierarchy. ) 

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

user = User.create(:preferences => %w( one two three ))
User.find(user.id).preferences    # raises SerializationTypeMismatch

When you specify a class option, the default value for that attribute will be a new instance of that class.

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

user = User.new
user.preferences.theme_color = "red"

Back