从数据库加载日期/时间类型时,Ecto将转换为Ecto.DateTime类型.从JSON字符串加载模型时,如何应用相同类型的转换
defmodule Rocket.User do
use Rocket.Model
schema "users" do
field :created_at, :datetime
field :name, :string
field :email, :string
field :password, :string
field :timezone, :string
end
end
iex(40)> Poison.decode!(~s({"created_at":"2015-01-21T06:05:10.891Z"}), as: Rocket.User)
%Rocket.User{created_at: "2015-01-21T06:05:10.891Z", email: nil, id: nil,
name: nil, password: nil, timezone: nil}
Run Code Online (Sandbox Code Playgroud)
If you are using Ecto 0.6.0, the best way is to use changesets:
Ecto.Changeset.cast Poison.decode!(data), %Rocket.User{},
~w(required_fields), ~w(optional_fields)
Run Code Online (Sandbox Code Playgroud)
Using changeset is actually recommended if you are receiving this as external data since you need to cast, filter and validate this data before adding it to the model. You can find more information about them in the Ecto introduction and also in the Ecto.Changeset module documentation.
但是还有一个问题:Ecto不知道如何将字符串转换为日期时间.但是,您可以通过使用自定义类型来教它如何使用.我在下面创建了一个模板,你只需要实现一个cast函数:
https://gist.github.com/josevalim/1ed574b388c32f056da1
然后在你的架构中:
timestamps type: Rocket.DateTime
Run Code Online (Sandbox Code Playgroud)
您可以在Ecto.Type文档中找到更多信息.我知道我们需要在Ecto中改进它,我认为我们至少应该能够以JSON中指定的格式解析日期时间.
| 归档时间: |
|
| 查看次数: |
1436 次 |
| 最近记录: |