Store又在包裹了上一节的序列化功能,是个简单又实用的功能,让你可以将某个栏位指定储存为Hash值。举例来说,上一节的settings也可以改用store来设定:
class User < ActiveRecord::Base
store :settings, accessors => [:sex, :url]
end
特别的是其中accessors
用来设定可以直接存取的属性,这样就可以像平常一样那样操作sex和url这两个属性,让我们进console实验看看:
> user = User.new(:sex => "male", :url => "http://example.com")
> user.sex
=> "male"
> user.url
=> "http://example.com"
> user.settings
=> {:sex => "male", :url => "http://example.com"}
因为store
就像使用hash一样,你也可以直接操作它,加入新的资料:
> user.settings[:food] = "pizza"
> user.settings
=> {:sex => "male", :url => "http://example.com", :food => "pizza"}