Rails 3 个序列化哈希值保存但不持久化

Rails 3 serialized hash values saving but not persisting

我有一个带有序列化文本列的模型。当我保存并重新加载记录时,这些值似乎仍然存在,但当我查询记录时,这些值消失了。

(为简单起见截断了下面的演示)

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 和不附加 Hash

从模型中删除 attr_accessible :pending_changes 和 attr_accessor :pending_changes,因为你在数据库中有一列,所以不需要使用 attr_accessible、attr_accessor。使用下面的模型代码试试。

class Subscription < ActiveRecord::Base
  serialize :pending_changes, Hash
end