Elixir/Phoenix 将 JSON 保存到 Postgres 数据库

Elixir/Phoenix saving JSON to Postgres Database

我在谷歌上搜索了很多方法来做到这一点。

我使用 phx.gen 生成器生成了一些 CRUD。我想在我的数据库中创建存储库并为其存储 Github activity。

我的迁移:

def change do
  create table(:coderepos) do
    add :name, :string
    add :description, :string
    add :repo_name, :string
    add :activity_data_raw, :jsonb
    timestamps()
  end
end

我的模特:

schema "coderepos" do
  field :activity_data_raw, :map, default: %{}
  field :name, :string
  field :description, :string
  field :repo_name, :string
  timestamps()
end

在创建我的新仓库时(通过生成的 HTML):

#Ecto.Changeset<
  action: :insert,
  changes: %{
    description: "Blah",
    name: "Blah",
    repo_name: "blah"
  },
  errors: [activity_data_raw: {"is invalid", [type: :map, validation: :cast]}],
  data: #App.Integrations.CodeRepo<>,
  valid?: false
>

我通过在控制器中 create 函数的 :error 响应中执行 IO.inspect(changeset) 来获得上面的变更集。

我的创建函数:

def create(conn, %{"code_repo" => code_repo_params}) do
  case Integrations.create_code_repo(code_repo_params) do
    {:ok, code_repo} ->
      conn
      |> put_flash(:info, "Code repo created successfully.")
      |> redirect(to: code_repo_path(conn, :show, code_repo))
    {:error, %Ecto.Changeset{} = changeset} ->
      render(conn, "new.html", changeset: changeset)
      IO.inspect(changeset)
  end
end

这是我在表单中提交的 JSON 部分(连同名称、描述和回购名称):

[{"week": 1532822400, "total": 6, "days": [0, 6, 0, 0, 0, 0, 0]}]

(只需将保存到我的数据库的操作与我在我的应用程序中执行的其他操作一起使用即可,因此没有任何问题)。

Postgres 10.4、Elixir 1.6.5/OTP 20、Phoenix 1.3.3、Phoenix Ecto 3.2

如有任何帮助,我们将不胜感激!

感谢 Elixir Slack 中的 @trevoke,现在可以正常使用了。您需要传递一张地图(我想这很明显,尽管我读过的其他地方听起来好像已经处理好了)。上面评论中的 Dogbert 基本上是在说同样的话。

create函数中:

raw = Map.get(code_repo_params, "activity_data_raw")
code_repo_params = Map.put(code_repo_params, "activity_data_raw", %{"data" => raw})