Search code examples
elixirphoenix-frameworkecto

Ecto: select records inserted_at a specific date


I have a very simple Ecto model:

defmodule MyApp.User do
  use MyApp.Web, :model

  schema "users" do
    field :name, :string
    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [])
    |> validate_required([])
  end
end

And a migration:

defmodule MyApp.Repo.Migrations.CreateUser do
  use Ecto.Migration

  def down do
    drop table(:users)
  end

  def change do
    drop_if_exists table(:users)
    create table(:users) do
      add :name, :string
      timestamps()
    end
  end

end

I want to select all users who were inserted_at a specific date (for example, today). What is the best way to do that?


Solution

  • I am unsure on how to do this through Ecto alone. So this answer is going to be specific to SQL. I have only tried this on PostreSQL.

    Attendance.Repo.all(from s in Something, 
                        where: fragment("date(inserted_at) = ?", ^~D[2017-02-06]))