我正在尝试在每种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 endschema.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数组
发布评论