3

I have the following class which is actually view model and I'm trying to initialize it based on the database model like so:

class Document

  @id   : Int64
  @name : String

  JSON.mapping(
    id: Int64,
    name: String,
  )

  def initialize(db_model)
    @id   = db_model.id
    @name = db_model.name
  end

end

Here is the example data model:

class DatabaseModel < ActiveRecord::Model

  @@connection_pool_capacity = 25
  @@connection_pool_timeout  = 0.03

  adapter postgres

  table_name database_model

  primary id  : Int
  field name  : String

end

However I'm getting the following error:

in src/models/document.cr:10: instance variable '@id' of Document must be Int64, not (Int16 | Int32 | Int64 | Int8 | Int::Null | UInt16 | UInt32 | UInt64 | UInt8)

I'd like to do this the most semantically correct way. Whats the best way to infer the correct type in this situation?

Tyler
  • 19,113
  • 19
  • 94
  • 151
  • Did you try declaring the specific `Int` type matching your database, probably `Int64`, in your database model? – Jonne Haß Apr 15 '18 at 09:15

1 Answers1

3

There is no inference involved in this error. It's just a type mismatch between expected Int64 for Document#@id vs Int returned by DatabaseModel#id.

There are two ways to resolve this: either convert dv_model.id to Int64 using #to_i64 or type DatabaseModel#id as Int64. The latter is probably the preferred way because usually there is no point in storing an I'd as different Int datatypes.

Johannes Müller
  • 5,581
  • 1
  • 11
  • 25