【问题标题】:date_select in form fails with "<field> is invalid"表单中的 date_select 失败并显示“<field> 无效”
【发布时间】:2015-07-08 03:41:32
【问题描述】:

我有这个模板,

<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 是我需要的还是我缺少其他东西?

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

    正如José Valim 更正,使用Ecto.Date 而不是:date 可以正确解决问题,并且不需要显式转换。


    看起来传递给创建函数的日期是一个地图。在插入之前,请尝试使用

    将其强制转换为日期

    Ecto.Date.cast(%{"day" =&gt; "1", "month" =&gt; "10", "year" =&gt; "2019"})

    我可以想象看起来像这样的代码

    selected_date = %{"day" => "1", "month" => "10", "year" => "2019"}
      |> Ecto.Date.cast
      |> Repo.insert!
    

    【讨论】:

    • insurance_expiry_map = bus_params["insurance_expiry"] {:ok, insurance_expiry_date} = Ecto.Date.cast(insurance_expiry_map) updated_bus_params = %{bus_params | "insurance_expiry" =&gt; insurance_expiry_date} changeset = Bus.changeset(%Bus{}, updated_bus_params) 我还在架构中将:date 类型更改为自定义Ecto.Date。做到了:)
    • 你不需要显式地转换它。错误在于您使用了:date 而不是Ecto.Date。我很快就会为此提出更好的错误。
    猜你喜欢
    • 2012-02-01
    • 2017-07-02
    • 2015-12-28
    • 1970-01-01
    • 2012-03-23
    • 2013-05-31
    • 2016-02-02
    • 1970-01-01
    相关资源
    最近更新 更多