Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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
share|improve this question
    
I thought serialized columns should be in a text field? – Dave Newton Mar 30 '15 at 23:16
    
Thanks, removing the "serialize" from the model did the trick. – Nona Mar 30 '15 at 23:33

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.