Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 315
icn Avatar asked Nov 15 '25 15:11

icn


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!