如何重新加载 ecto 记录?

how to reload an ecto record?

我有这段代码可以将记录插入数据库。完成此操作后,我需要获取新记录的 ID 以传递给客户端。

  msg_record = %Message{
    fromEmail: params["fromEmail"],
    body: params["body"],
    room: room_id
  }
  Repo.insert!(msg_record)

问题是,在这样做之后 msg_record.id 仍然是空的。

在 Rails 中我会做 msg_record.reload.id - 有一些等效的方法吗?

我想我没有仔细阅读文档。

这是在 HexDocs on Ecto 中找到的:

iex> weather = %Weather{temp_lo: 0, temp_hi: 23}

iex> Repo.insert!(weather)

After persisting weather to the database, it will return a new copy of %Weather{} with the primary key (the id) set. We can use this value to read a struct back from the repository:

所以在我的例子中,我可以简单地重新分配变量:

msg_record = Repo.insert!(msg_record)