Rails 5 , sqlite3 using array as column/ attribute issue

icn

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!

user11831257

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Rails Associations: SQLite3::SQLException: no such column

Rails 5 uuid issue with sqlite

Performance issue when using multiple threads with sqlite3

Rails - SQLite3::SQLException: near "USING": syntax error

How to fix sqlite3 error using rails and ruby

Pandas Issue using user_agent attribute on column

issue using rails console building a Rails 5 api

Using generated columns to cast existing column to float in sqlite3

Import CSV into SQLite3 Using Column Subset

How to format column width in SQLite3 using python?

Using Python SQLite3 to find latin alphabets in column

Issue with replacing NULL sqlite3 database column values with other types in Python 3?

Cannot set new attribute on User model (using Devise & Rails 5)

Using Rails 5 enum with PG array

Array issue in rails and highcharts

Rails ActiveRecord SQlite3 datatype mismatch error on change_column from string to text

lambda uuid generator for id's model in rails5 with sqlite3

Rails 5 and MongoDB: Specified 'sqlite3' for database adapter, but the gem is not loaded

HTML 5 Angular 10: Display array attribute values using EXL

Ruby on Rails - Sqlite3

I want to put string and array data in sqlite3 in ruby on rails

How to Remove SQLite3 from Rails but keep using ActiveRecord/Mongo?

Rails 5 route, url issue

Rails 5 issue with doing a search

rails 5 mysql adapter issue

Generated column using string replace function throws a syntax error in SQLite3

How can I use column names to specify what to write to using sqlite3?

Rails: select array based on attribute

Rails: array column inside nested attribute params wrong number of arguments (given 0, expected 1..2)