Creating Ecto model and migration with timestamp field having only inserted_at fileld

363 views
Skip to first unread message

me.m...@gmail.com

unread,
Oct 21, 2015, 2:30:12 PM10/21/15
to phoenix-talk
I have few tables in which data is never updated (some time series data). The data is inserted only once, that's it. I don't want updated_at field in the table. What is the recommended way to achieve this.

thanks
miwee

Steve Domin

unread,
Oct 21, 2015, 3:06:06 PM10/21/15
to phoenix-talk, me.m...@gmail.com
Hello miwee,

You can pass options to the `timestamps` macro when defining the schema for your model. If you want to disable the updated_at field you can do the following:

defmodule MyApp.User do
  use Ecto.Model

  import Ecto.Changeset
  import Ecto.Query, only: [from: 1, from: 2]

  schema "users" do
    field :name, :string

    timestamps(updated_at: false)
  end
end

In your migration, instead of using the timestamps function you can create the `inserted_at` column manually:

MyApp.Repo.Migrations.AddUsers do
  use Ecto.Migration

  def change do
    create table(:users) do
      add :name, :string
      add :inserted_at, :datetime
    end
  end
end

And that's it, this should work.

me.m...@gmail.com

unread,
Oct 21, 2015, 4:03:17 PM10/21/15
to phoenix-talk, me.m...@gmail.com
Hello Steve,

It works like charm! many thanks.

miwee
Reply all
Reply to author
Forward
0 new messages