在凤凰应用程序中,我想将会话记录保存到Postgres数据库,expires
字段为12小时。我的会话模型将过期字段设置为Ecto.DateTime
。
模型
schema "sessions" do
field :key, :string
field :expires, Ecto.DateTime
field :user_id, :integer
timestamps()
end

当验证在登录控制器中成功时,我构建会话对象并将其发送到会话控制器中的创建功能。 Timex用于确定从现在起12小时的时间。
登录控制器
{:ok, session_expiry} = Ecto.DateTime.cast(Timex.to_datetime(Timex.shift(Timex.now, hours: 12)))
# Returns {:ok, #Ecto.DateTime<2017-07-13 20:56:25.969059>}
session_object = %{
"key" => encrypted_auth_code,
"expires" => session_expiry,
"user_id" => user_id
}
SessionController.create(%{"data" => data = %{"type" => "session", "attributes" => session_object}})
&#13;
会话控制器
def create(%{"data" => data = %{"type" => "session", "attributes" => _session_params}}) do
changeset = Session.changeset(%Session{}, Params.to_attributes(data))
IO.inspect _session_params
case Repo.insert(changeset) do
{:ok, session} ->
IO.puts "success"
{:error, changeset} ->
IO.puts "failure"
end
end
&#13;
在会话控制器中,行case Repo.insert(changeset) do
会引发以下错误:
no function clause matching in Ecto.Adapters.Postgres.DateTime.encode_date/1
如果我将会话模型中 expires 字段的类型更改为Ecto.Date
,则会成功创建数据库记录,但没有时间。
为了将Ecto.DateTime字段保存到数据库,我需要更改什么?
答案 0 :(得分:3)
如果Ecto.Date
正常工作,数据库中字段的类型可能是date
而不是utc_datetime
(PostgreSQL中的timestamp
)。将其更改为utc_datetime
应该可以解决错误。如果您使用迁移来创建表,则可以创建一个新的表来改变列的类型,如下所示:
def up do
alter table(:sessions) do
modify :expires, :utc_datetime
end
end
def down do
alter table(:sessions) do
modify :expires, :date # old type here
end
end