我有一个带有序列化文本列的模型。当我保存并重新加载记录时,这些值似乎仍然存在,但当我查询记录时,这些值消失了。
(为简单起见,下面的演示被截断了)
class Subscription < ActiveRecord::Base
serialize :pending_changes, Hash
attr_accessible :pending_changes
attr_accessor :pending_changes
end
class AddPendingChangesToSubscriptions < ActiveRecord::Migration
def change
add_column :subscriptions, :pending_changes, :text
end
end
s = Subscription.new
s.pending_changes = {foo: "bar"}
s.save
# => true
s.reload.pending_changes
# => {foo: "bar"}
Subscription.last.pending_changes
# => nil
将 {"foo"=> "bar"}
保存为值时会发生同样的事情。
我还注意到,当 save
被调用时,生成的 SQL 查询如下:
UPDATE 'subscriptions' SET 'updated_at' = '2017-12-01 23:46:05', 'pending_changes' = '--- {}\n' WHERE 'subscriptions'.'id' = 2
根据对类似问题的回答,我确定数据库列的数据类型是 text
并且我尝试使用 serialize :column_name
有和没有附加哈希
。
最佳答案
从模型中删除 attr_accessible :pending_changes 和 attr_accessor :pending_changes,因为你在数据库中有一列,所以不需要使用 attr_accessible,attr_accessor。使用下面的模型代码并尝试。
class Subscription < ActiveRecord::Base
serialize :pending_changes, Hash
end
关于mysql - Rails 3 序列化哈希值保存但不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47602967/