使用`created_at`而不是`inserted_at`

时间:2016-08-19 11:07:16

标签: phoenix-framework ecto

我想使用旧的Rails MySQL数据库/表而不用新的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

网络/模型/ 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
[...]

但是我得到以下错误:

Screenshot

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

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

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文件中(在架构部分中)。

答案 1 :(得分:1)

除了上述答案外,跨上下文设置此内容的最佳方法是:

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

相关问题