【问题标题】:How to read/write a Rails ActiveRecord datetime field using Ecto?如何使用 Ecto 读取/写入 Rails ActiveRecord 日期时间字段?
【发布时间】:2017-06-13 04:56:00
【问题描述】:

我正在使用 Phoenix 框架将用 Rails 编写的 API 重写为 Elixir。

主网站使用Rails,并将继续使用Rails。但是我希望 API 使用 Elixir。

我需要能够从我的 Elixir API 项目中读取 created_at 字段。

defmodule Example.Recipe do
  use Ecto.Schema

  schema "recipes" do
    field :name, :string
    field :description, :string
    field :slug, :string
    field :created_at ???datetime?
  end
end

如何从我的 Elixir API 正确读取 created_atupdated_at 字段?

我知道 Ecto 使用 Ecto.DateTime,但这兼容吗?

【问题讨论】:

    标签: ruby-on-rails ruby elixir phoenix-framework ecto


    【解决方案1】:

    首先,Ecto 使用inserted_at 列来跟踪记录首次插入数据库的时间,Rails 使用created_at

    您应该覆盖插入的列名称:

    在 Ecto 架构定义中,timestamps 接受为inserted_at 和 updated_at 指定替代列名的选项。

    改变:

    更改 web/models/your_model.ex 中的时间戳定义:

    schema "your_model" do
      field :login, :string
    
      timestamps()
    end
    

    schema "your_model" do
      field :login, :string
    
      timestamps inserted_at: :created_at
    end
    

    要全局执行此操作,请查看 https://hexdocs.pm/ecto/Ecto.Schema.html#module-schema-attributes

    def model do
      quote do
        use Ecto.Schema
        @timestamps_opts inserted_at: :created_at
    
        import Ecto
        import Ecto.Changeset
        import Ecto.Query
      end
    end
    

    进一步references of migration

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 2011-01-23
      相关资源
      最近更新 更多