我在我的模型上设置了数组,当我将数组写入我的记录时,它显示 COMMIT true,但在返回一个空数组后立即检查该记录上的字段。
型号:
class Feature < ActiveRecord::Base
serialize :content, Array
attr_accessible :content
end
迁移:
class AddContentToFeatures < ActiveRecord::Migration
def change
add_column :features, :content, :text, array: true, default: []
end
end
我尝试过的以及各种符号和字符串语法是这样的:
> f=Feature.new
> f.content_will_change! #i feel like i shouldn't have to do this
> f.content = ['sadasd','asdasd']
> f.save!
BEGIN
COMMIT
=> true
> f.content
=> []
如何在模型上持久化数组?
最佳答案
如果您正在使用 native PostgreSQL 数组(因为您在迁移中使用了 array: true
),那么您根本不应该使用 serialize
。 serialize
用于在数据库中存储YAML:
serialize(attr_name, class_name_or_coder = Object)
If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, then specify the name of that attribute using this method and it will be handled automatically. The serialization is done through YAML. If
class_name
is specified, the serialized object must be of that class on assignment and retrieval. OtherwiseSerializationTypeMismatch
will be raised.
因此,serialize
只是将 YAML 编码的对象存储在数据库的 text
列中。但是 PostgreSQL、Rails4 中的 ActiveRecord 和底层的 PostgreSQL 驱动程序都可以理解数组而没有所有 YAML 的不愉快之处。
在迁移中保留 array: true
,从模型中删除 serialize :content, Array
,它应该可以正常工作。作为额外的奖励,您将能够使用所有 PostgreSQL's array operators and functions要查询您的内容
,serialize
不允许您这样做。
关于ruby-on-rails - Rails 无法写入数据库中的序列化数组字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35443041/