使用 `created_at` 而不是 `inserted_at`

Use `created_at` instead of `inserted_at`

我想使用旧的 Rails MySQL database/table 而不用新的 Elixir 应用程序更改它。很明显我运行变成了created_atinserted_at的问题。 https://hexdocs.pm/ecto/Ecto.Schema.html#timestamps/1说我可以解决。但是我无法让它工作。

这是我的做法:

mix phoenix.new address_book --database mysql
cd address_book
mix phoenix.gen.html User users first_name last_name
mix phoenix.server

web/models/user.ex

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

  schema "users" do
    field :first_name, :string
    field :last_name, :string

    timestamps([{:created_at,:updated_at}])
  end
[...]

但是我得到以下错误:

我该如何解决这个问题?

您没有使用正确的参数调用时间戳函数。它需要选项,所以它应该是:

timestamps(inserted_at: :created_at)

或:

timestamps([{inserted_at: :created_at}])

您正在呼叫:

timestamps(created_at: :updated_at)

由于没有检查 created_at 选项,这不会更改正在使用的时间戳。

您可以使用以下方法为您的所有架构配置此功能:

  @timestamps_opts inserted_at: :created_at

在您的 web.ex 文件中(在架构部分)。

除了上面的答案之外,在上下文中设置它的最佳方法是:

defmodule MyApp.Schema do
  defmacro __using__(_) do
    quote do
      use Ecto.Schema
      @timestamps_opts inserted_at: :created_at
    end
  end
end

然后,不必在每个模式中定义它,您可以 use MyApp.Schema

我在我的 phoenix 应用程序中使用此模式,该模式使用由 rails 生成的共存数据库模式。

https://hexdocs.pm/ecto/Ecto.Schema.html