我有这个模板,
<div class="form-group">
<label>Insurance Expiry : </label>
<%= date_select f, :insurance_expiry, class: "form-control" %>
</div>
和迁移有,
def change do
create table(:buses) do
# snipped
add :insurance_expiry, :date, default: Ecto.Date.local
end
并在db模型中,
schema "buses" do
# snipped
field :insurance_expiry, :date
end
关于创建操作的调试信息,
[info] Processing by BusMan.BusController.create/2
Parameters: %{"_csrf_token" => "PDkIZycHTRJsEzwOEBJRXxo6MVIFJgAAHla/FI4Y5PQxTYdk/XakNg==", "_utf8" => "✓", "bus" => %{"bus_no" => "138", "chassis_no" => "nTHSNTH", "engine_no" => "RCHR989", "insurance_expiry" => %{"day" => "1", "month" => "10", "year" => "2019"}, "models" => "NTHRCG898", "reg_no" => "TN21W0613", "year_of_registration" => "1990"}, "format" => "html"}
表单提交失败,并显示:
Oops, something went wrong! Please check the errors below:
Insurance expiry is invalid
我只想输入日期,date_select
是我需要的还是我错过了其他的东西?
答案 0 :(得分:8)
正确José Valim,使用Ecto.Date
而不是:date
正确解决问题,并且不需要显式投射。
看起来传递给create函数的日期是一张地图。在插入之前,请尝试使用
将其投射到日期 Ecto.Date.cast(%{"day" => "1", "month" => "10", "year" => "2019"})
我可以想象看起来像
的代码selected_date = %{"day" => "1", "month" => "10", "year" => "2019"}
|> Ecto.Date.cast
|> Repo.insert!