Search code examples
ruby-on-railssqliteserializationruby-on-rails-5

Rails 5 , sqlite3 using array as column/ attribute issue


Here is how I use array in a rails 5 model in migration

  t.text :diagnoses, array: true, default: []

in model

class Patient < ApplicationRecord
  serialize :diagnoses, Array
end

in my seed method I am doing it like

  patient = Patient.create(first_name: 'John', last_name: 'Smith', admission: a)
  patient.diagnoses = [1, 2]
  patient.save!

It give an error as

ActiveRecord::SerializationTypeMismatch: can't dump `diagnoses`: was supposed to be a Array, but was a Integer. -- 0

Thanks for any help!


Solution

  • A while ago, I encountered this exact issue. I found the following workaround:

    • In your migration file:

      t.text :diagnoses, array: true
      
    • Then in model:

      class Patient < ApplicationRecord
        serialize :diagnoses
      
        after_initialize do |patient|
          patient.diagnoses= [] if patient.diagnoses == nil
        end
      end
      
    • The after_initialize callback will be called whenever an Active Record object is instantiated, either by directly using new or when a record is loaded from the database.