在Rails 2.3.6中我将一些序列化数据存储在数据库字段中。在Rails中输出序列化对象
在我的数据库我的“feed_event.data”字段存储为文本,它是(例如)等于:
{:post=>{:pic=>"http://s3.amazonaws.com/criticalcity/datas/3524/big_thumb/send-a-letter.jpg", :name=>"Un’istruzione perfetta", :id=>1995, :authors=>"Delilah"}, :user=>{:pic=>"http://s3.amazonaws.com/criticalcity/avatars/537/thumb/DSCN2744.JPG", :name=>"Luci!", :id=>537}}
现在我需要输出这一领域作为字符串(正是因为它是在数据库),但是当我问:
puts feed_event.data
输出:
postpichttp://s3.amazonaws.com/criticalcity/datas/3524/big_thumb/send-a-letter.jpgnameUn’istruzione perfettaid1995authorsDelilahuserpichttp://s3.amazonaws.com/criticalcity/avatars/537/thumb/DSCN2744.JPGnameLuci!
为什么? 如何将它输出为yaml字符串?
UPDATE
为了创建它,我有这个在我的FeedEvent模型:
class FeedEvent < ActiveRecord::Base
has_many :user_feed_events, :dependent => :destroy
has_many :users, :through => :user_feed_events
serialize :data
end
而且为了创建一个新的FeedEvent元素我做的:
feed = FeedEvent.create(:event_type => "comment #{commentable_type}", :type_id => id, :data => {:user => {:id => user.id, :name => user.name, :pic => user.avatar.url(:thumb)}, :comment => {:id => id, :body => body, :commentable_id => commentable_id, :commentable_type => :commentable_type, :commentable_name => commentable.name}})
更新#2
以下nzifnab的提示我用.to_yaml方法,但什么Rails的输出在这种情况下是:
data: "--- \n:post: \n :pic: http://s3.amazonaws.com/criticalcity/datas/3524/big_thumb/send-a-letter.jpg\n :authors: Delilah\n :name: \"Un\\xE2\\x80\\x99istruzione perfetta\"\n :id: 1995\n:user: \n :pic: http://s3.amazonaws.com/criticalcity/avatars/537/thumb/DSCN2744.JPG\n :name: Luci!\n :id: 537\n"
兼评“连载:数据”模型输出。
感谢, 奥古斯托
你如何序列化它?哈希,数组,其他吗? – apneadiving
我更新了这个问题的一些细节。 – Augusto
回应您的最新更新。这不是你想要的价值吗?这不就是存储在数据库中的确切字符串吗?如果你打开了一个MySql控制台会话并做了'SELECT data FROM feed_events WHERE data IS NOT NULL LIMIT 1',那么保存的字符串是不是像这样?让我知道如果你正在寻找其他东西... – nzifnab