7

我有这个模板,

<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是我需要的还是我错过了其他东西?

4

1 回答 1

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!
于 2015-07-08T07:30:45.450 回答