gpt4 book ai didi

oop - 已创建 预期创建为 (Time | Nil) 但得到 (Float64 | String)

转载 作者:行者123 更新时间:2023-12-05 05:03:35 25 4
gpt4 key购买 nike

我对这个 amber 框架、crystal lang 和一般的面向对象编程是新手。我正在学习教程并尝试使用这个脚手架创建一个简单的表单

amber g scaffold item name:string path:string type:string size:float created:date

我可以看到这个类已经在模型文件夹中创建了

class Item < Granite::Base
connection pg
table items

column id : Int64, primary: true
column name : String?
column path : String?
column type : String?
column size : Float64?
column created : Time?
timestamps

end

当我启动应用程序并厌倦了插入新项目时,我收到了这个错误

Created Expected created to be (Time | Nil) but got (Float64 | String).

这是.slang 形式的代码

== form(action: "/items/#{item.id.to_s}", method: item.id ? :patch : :post) do
== csrf_tag
.form-group
== text_field(name: "name", value: item.name, placeholder: "Name", class: "form-control")
.form-group
== text_field(name: "path", value: item.path, placeholder: "Path", class: "form-control")
.form-group
== text_field(name: "type", value: item.type, placeholder: "Type", class: "form-control")
.form-group
== text_field(name: "size", value: item.size, placeholder: "Size", class: "form-control")
.form-group
== text_field(name: "created", value: item.created, placeholder: "Created", class: "form-control")
== submit("Submit", class: "btn btn-success btn-sm")
== link_to("Back", "/items", class: "btn btn-light btn-sm")

我猜想当我输入像 2020-01-01 00:01:00 这样的值时,它被作为字符串处理,但我需要将其转换为时间类型。我认为这需要在相关的 Controller 文件上发生,但我不知道该怎么做。

这是我尝试创建新项目时执行的代码。

  def create
item = Item.new item_params.validate!
if item.save
redirect_to action: :index, flash: {"success" => "Item has been created."}
else
flash[:danger] = "Could not create Item!"
render "new.slang"
end
end

谢谢,咕噜咕噜

最佳答案

我能够通过创建一些新功能来完成这项工作

class Item < Granite::Base
...
def set_id (id : Int64)
@id = id
end
def set_name (name : String)
@name = name
end
def set_filetype (filetype : String)
@filetype = filetype
end
def set_filesize (filesize : Float64)
@filesize = filesize
end
def set_filepath (filepath : String)
@filepath = filepath
end
def set_created (cr : Time)
@created = cr
end

然后在初始化一个空项目后使用它们

item = Item.new
item.set_name(params[:name])
item.set_filetype(params[:filetype])
item.set_filesize(params[:filesize].to_f64)
item.set_filepath(params[:filepath])
item.set_created(Time.parse(params[:created],"%Y-%m-%d %H:%M:%S %z", Time::Location::UTC))

虽然我认为这不是最好的解决方案。由于此 parmas 对象将所有内容存储为字符串,我怀疑当您使用此初始化新项目时,像“2020-01-01 00:01:00 UTC”这样的字符串不会转换为适当的时间类型。 Int 或 Float 等其他类型似乎在没有问题的情况下也能正常工作。

item = Item.new item_params.validate!

关于oop - 已创建 预期创建为 (Time | Nil) 但得到 (Float64 | String),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61575193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com