dipth
Storing date from date_select
How does one go about storing datetime values from a date_select field in the database?
Here is my Ecto model:
defmodule MyApp.User do
use MyApp.Web, :model
schema "users" do
field :birthday, :utc_datetime
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:birthday])
end
end
Here is my template:
<%= date_select f, :birthday, builder: fn b -> %>
<%= b.(:day, prompt: "", class: "custom-select") %> /
<%= b.(:month, prompt: "", class: "custom-select") %> /
<%= b.(:year, options: Timex.now.year..(Timex.now.year - 100), prompt: "", class: "custom-select") %>
<% end %>
Here is my controller:
def update(conn, %{"user" => user_params}) do
user = Guardian.Plug.current_resource(conn)
changeset = User.changeset(user, user_params)
case Repo.update(changeset) do
{:ok, _user} ->
conn
|> put_flash(:success, gettext("Profile updated!"))
|> redirect(to: public_profile_path(conn, :show, user))
{:error, changeset} ->
conn
|> render("edit.html", changeset: changeset)
end
end
I can successfully submit the form, but the birthday is never written to the database
Most Liked Responses
dsissitka
I wonder if you need to use field :birthday, :date.
I wonder if that’s because you’re using :utc_datetime and you aren’t passing in a time.
dipth
You are right. Changing the column in the database to :date fixes the problem.
I find it weird though that it shouldn’t be possible to store a date value in a datetime field and just have the time-part assumed as midnight.
In this case it isn’t a big problem, but there might be cases where it is important to have the time-part in the database as well as the date in case you want to perform timezone-sensitive checks on the date…
radar
What do the logs show when that action is hit?
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #javascript
- #podcasts
- #code-sync
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








