Nona
Nona

Reputation: 5472

Can't save a Rails 4.2 array in Postgres array column

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

migration

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

Upvotes: 0

Views: 705

Answers (1)

Semjon
Semjon

Reputation: 1023

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.

Upvotes: 1

Related Questions