Search code examples
elixirecto

In Elixir/Ecto, how do I change the default value of an existing naive_datetime field to now in a given timezone?


Suppose I have this schema:

  schema "events" do
    field :start, :naive_datetime
  end

I'd like to set the default value of the start field to roughly the time when the /events/new page loads ("now"). Let's ignore the objection that users won't normally want the event to start actually right now, and suppose we know in advance the timezone (e.g., "US/Mountain") where "now" should be evaluated.


Solution

  • You could do that at the changeset level.

    def create_changeset(event, attrs) do
     event
     |> cast(attrs, [:start])
     |> put_start()
    end
    
    def put_start(%{changes: %{start: _start}} = changeset), do: changeset
    
    def put_start(changeset) do
     changeset
     |> put_change(:start, current_time(timezone))
    end