论坛首页 编程语言技术论坛

关于Rails serialized属性

浏览 2225 次
精华帖 (0) :: 良好帖 (11) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-04-23  
Active Record 有个serialized属性,简单说说关于这个属性的一些东西

1. 干什么用的


    实现在文本字段存储序列化的值.即,序列,哈希表,数组等.   

2. serialized怎么用

以下是官方API中的例子
  class User < ActiveRecord::Base
    serialize :preferences # users表中有preferences字段,类型是文本的
  end

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


  class User < ActiveRecord::Base
    serialize :preferences, Hash#指定了序列化类型
  end

  user = User.create(:preferences => %w( one two three ))#赋值是array类型
  User.find(user.id).preferences    # 提示序列化类型不匹配错误raises SerializationTypeMismatch


3. 帮助理解的例子

数据库有个settings表,该表有id和文本的menu属性
#model描述
class Setting < ActiveRecord::Base
  serialize :menu
end


 # 创建记录
 s = Setting.new
 => #<Setting id: nil, menu: nil>
  
 # 分配序列menu值,例子2个,可以更多
 s.menu = [ 'subscription', 'membership' ]
 => ["subscription", "membership"]
  
 # 读取该值,以便验证
 s.menu
 => ["subscription", "membership"]
  
 # 保存记录
 s.save
 => true

数据库存储数据如下:
 id: 1
 menu: --- \n- subscription\n- membership
#So it was serialized to YAML correctly.查看数据库,可以知道成功序列化成YAML格式

重新读取
 s2 = Setting.find(1)
=> #<Setting id: 1, menu: ["subscription", "membership"]>
 
 # Read the menu attribute and So it was deserialized too 
 # 表明反序列化成功
s2.menu
 => ["subscription", "membership"]



4. 在什么情况下使用

这个API看不出来,我们可以假设一个情景. 当前,SNS网络比较流行,对于当前用户User的Blog可能有很多用户访问, 那么,用户之间可能是好友关系.这就需要判断,而这个判断经常会用到, 那么,或者我们需要查询一个类似friendship-status表,或者,需要一个很长的针对user id的查询.

显然,面对这样的情景,都会需要比较长的时间.那么,serialized在这种情况下,比较好用.就是把用户id序列化到文本属性就可以了.

5. Rails 2.1以后为什么不能保存


#会执行失败
def add_to_friend_ids_cache(friend_id)
self.friend_ids_cache << friend_id unless self.friend_ids_cache.include?(friend_id)
self.save
end

def add_to_friend_ids_cache(friend_id)
self.friend_ids_cache_will_change!#_will_change! method for handling dirty objects
self.friend_ids_cache << friend_id unless self.friend_ids_cache.include?(friend_id)
self.save
end


论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics