0

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
2
  • I thought serialized columns should be in a text field? Commented Mar 30, 2015 at 23:16
  • Thanks, removing the "serialize" from the model did the trick. Commented Mar 30, 2015 at 23:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.