ruby-on-rails - Rails 无法写入数据库中的序列化数组字段

标签 ruby-on-rails arrays postgresql activerecord rails-activerecord

我在我的模型上设置了数组,当我将数组写入我的记录时,它显示 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),那么您根本不应该使用 serializeserialize用于在数据库中存储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. Otherwise SerializationTypeMismatch 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/

相关文章:

java - 检查数组中模式的递归方法

php - 来自 html 表单的 pgsql 日期范围查询

postgresql - 如何在postgresql中添加时间段,其中时间段有年、月、日?

postgresql - 如何获取 INNER join 的计数和所有项目的计数?

ruby-on-rails - 如何对 quickbooks-ruby 进行故障排除

ruby-on-rails - 如何让我的 rails 应用程序解决错误?

ruby-on-rails - 给数组设置一定的大小和内容

ruby-on-rails - 如何使用正则表达式删除 memcached 中的键(使用 Dalli+RoR)。

c++ - 如何在 C++ 中搜索字符串数组

php - PHP 数组代码帮助