我有以下类实际上是视图模型,我正在尝试基于数据库模型初始化它,如下所示:
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
以下是示例数据模型:
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
但是我收到以下错误:
在src / models / document.cr中:10:Document的实例变量'@id'必须是Int64,而不是(Int16 | Int32 | Int64 | Int8 | Int :: Null | UInt16 | UInt32 | UInt64 | UInt8)
我想以最语义正确的方式做到这一点 . 什么是在这种情况下推断出正确类型的最佳方法?
1 回答
此错误不涉及推断 . 这只是
Document#@id
与DatabaseModel#id
返回的Document#@id
预期Int64
之间的类型不匹配 .有两种方法可以解决此问题:使用
#to_i64
将dv_model.id
转换为Int64
或将DatabaseModel#id
键入Int64
. 后者可能是首选方式,因为通常没有必要将I'作为不同的Int数据类型存储 .