无法在Postgres数组列中保存Rails 4.2数组 [英] Can't save a Rails 4.2 array in Postgres array column

查看:69
本文介绍了无法在Postgres数组列中保存Rails 4.2数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在每种Dictionary模型上保存一组术语(我希望基本上能够搜索标签)。因此,terms = [ apple, pear, fruit]可能是我要在Dictionary模型的每个实例上保存的术语数组的一个示例。以前,术语是序列化的文本列。然后,我将其更改为尝试使用Postgres数组数据类型,如下所示。当我尝试更新模型时(例如,dictionary_example1.terms = [ fruit, pineapple],然后调用save),所有存储的都是空数组[]。我在做什么错?

I'm trying to save an array of terms on each Dictionary model (I want to be able to search tags basically). So terms=["apple", "pear", "fruit"] could be one example of a term array I'm trying to save on each instance of a Dictionary model. Previously, terms was a serialized text column. I then changed it to try and take advantage of the Postgres array datatype as follows. When I try to update a model (e.g., dictionary_example1.terms = ["fruit", "pineapple"] followed by a call to save), all that is stored is an empty array []. What am I doing wrong?

Model.rb

class Dictionary < ActiveRecord::Base
  serialize :terms, Array

end

schema.rb

create_table "clinical_trials", force: :cascade do |t|
    t.string   "terms",             array: true
  end

迁移

class ChangeTermsToArray < ActiveRecord::Migration
    def change
      change_column :dictionaries, :terms, "varchar[] USING (string_to_array(terms, ','))"
  end
end


推荐答案

序列化用于将ruby对象序列化为字符串,以便将ruby对象保留在数据库中。最受欢迎的是YAML序列化器。 Rails 4具有对Postgresql数组的内置支持,自4.0起,因此我们不需要为模型中的数组属性设置字符串序列化器。

serialize in ActiveRecord is used for serialization of ruby objects into string in order to persist ruby object in database. The most popular is YAML serializer. Rails 4 has a builtin support of Postgresql arrays since 4.0, so we do not need to set string serializer for array attribute in model.

这篇关于无法在Postgres数组列中保存Rails 4.2数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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