2017-06-13 64 views
1

我正在使用Phoenix Framework将使用Rails编写的API重写为Elixir。如何使用Ecto读取/写入Rails ActiveRecord datetime字段?

主要网站使用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 

如何从我的药剂API正确读取created_atupdated_at领域?

我知道Ecto使用Ecto.DateTime但是兼容?

回答

2

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

你应该过度骑插入,在列名:

在一个外生模式定义,时间戳接受选项指定为inserted_at和替代的updated_at列名。

变化:

更改显示在web /模型/ 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