Rails可以不写在数据库序列化数组字段 [英] Rails can't write to serialized array field in database

查看:225
本文介绍了Rails可以不写在数据库序列化数组字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的模式阵列,并成立了,当我去写的阵列到我的记录它说COMMIT真实的,但检查这个记录现场后立即返回一个空数组。

I have the array on my model and set up, and when I go to write the array onto my record it says COMMIT true, yet checking the field on that record immediately after returns an empty array.

型号:

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

我试了一下,各种符号和字符串语法一起,是这样的:

What I tried, along with various symbol and string syntaxes, is this:

> 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
=> []

我如何坚持阵列上的模式吗?

How do I persist the array on the model?

推荐答案

如果您在使用本机PostgreSQL的数组(这你是因为你有数组:真正的在你的迁移),那么你不应该使用连载可言。 <一href=\"http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html#method-i-serialize\"相对=nofollow> 连载 用于存储YAML数据库:

If you're using native PostgreSQL arrays (which you are since you have array: true in your migration) then you shouldn't use serialize at all. serialize is used to store YAML in the database:

连载(attr_name,class_name_or_ codeR =对象)

serialize(attr_name, class_name_or_coder = Object)

如果你有需要被保存到数据库中作为对象,和作为同一对象中检索一个属性,然后指定使用这种方法,其属性的名称,它会被自动处理。序列化是通过YAML完成。如果指定了 CLASS_NAME 时,序列化对象必须在分配和检索该类的。否则 SerializationTypeMismatch 将提高。

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.

所以连载只存储一个文本中的一个YAML恩codeD对象中的数据库列。但是PostgreSQL里,ActiveRecord的在Rails4,和底层的PostgreSQL驱动都明白阵列没有所有的不愉快YAML

So serialize simply stores a YAML-encoded object inside a text column in the database. But PostgreSQL, ActiveRecord in Rails4, and the underlying PostgreSQL driver all understands arrays without all the YAML unpleasantness.

数组:真正的在迁移,删除连载:从你的模型内容,阵列,和它应该工作的罚款。作为额外的奖励,你就可以使用所有 PostgreSQL的数组运算符和功能来查询您的内容连载不允许你这样做。

Leave the array: true in your migration, remove the serialize :content, Array from your model, and it should work fine. As an added bonus, you'll be able to use all of PostgreSQL's array operators and functions to query your content, serialize doesn't allow you to do this.

这篇关于Rails可以不写在数据库序列化数组字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆