无法在Postgres数组列中保存Rails 4.2数组

编程入门 行业动态 更新时间:2024-10-24 10:18:26
本文介绍了无法在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数组

本文发布于:2023-10-24 16:55:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524494.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   Postgres   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!