** (ArgumentError) could not encode datetime: {2016, 10, 11}
This error happens when you are by-passing Ecto's Query API by
using either Ecto.Adapters.SQL.query/4 or Ecto fragments. This
makes Ecto unable to properly cast the type. For example:
now = Ecto.DateTime.utc |> Calecto.DateTimeUTC.cast
from u in User, where: fragment("(?).wall_time > ?", u.start_datetime, ^now)
In the query above, Ecto is unable to know the variable "now" is
being compared to a datetime due to the fragment and is therefore
unable to cast it. You can fix this by explicitly telling Ecto
which type must be used:
fragment("(?).wall_time > ?",
u.start_datetime,
type(^now, :datetime))
Or by implementing the Ecto.DataType protocol for the given value.
with the following model
defmodule PhoenixMessagingGateway.SmsMessage do
use PhoenixMessagingGateway.Web, :model
use Timex
schema "sms_messages" do
field :from_number, :string
field :to_number, :string
field :body, :string
field :gateway_sid, :string
field :gateway_status, :string
field :gateway_error_code, :string
field :gateway_error_message, :string
field :scheduled_to, Timex.Ecto.DateTimeWithTimezone
field :enqueued_at, Timex.Ecto.DateTimeWithTimezone
field :sent_at, Timex.Ecto.DateTimeWithTimezone
field :failed_at, Timex.Ecto.DateTimeWithTimezone
field :phone_gateway, :string, default: "twilio"
timestamps()
end
@allowed_fields ~w(from_number to_number body scheduled_to)a
@required_fields @allowed_fields
def create_changeset(struct, params \\ %{}) do
struct
|> cast(params, @allowed_fields)
|> maybe_set_scheduled_to
|> validate_required(@required_fields)
|> update_change(:from_number, &format_phone_number/1)
|> update_change(:to_number, &format_phone_number/1)
|> validate_format(:from_number, ~r/\A\d{10}\z/)
|> validate_format(:to_number, ~r/\A\d{10}\z/)
end
defp format_phone_number(phone) do
if phone != nil do
String.replace(phone, ~r/\D/, "")
end
end
defp maybe_set_scheduled_to(struct) do
if get_change(struct, :scheduled_to) do
struct
else
put_change(struct, :scheduled_to, Timezone.convert(Timex.now, "UTC"))
end
end
end
and my scheduled_to is a datetimetz following examples provided
getting the following error
with the following model
and my scheduled_to is a
datetimetz
following examples providedHere are my versions
Looking at the source code when I manually call
Timex.Ecto.DateTimeWithTimezone
on a datetime it strips my TZ info and this is the generated queryIs this a bug or am I doing something completely off?