我一直在尝试在postgresql中的jsonb列中保存JSON,我已经尝试了this教程并且还开始阅读Ecto API以及Postgrex但是无法使其工作,一个工作示例会让我感到高兴:)到目前为止,我已将此添加到我的配置
config :bonsai, Bonsai.Repo,
adapter: Ecto.Adapters.Postgres,
username: "demo",
password: "demo123",
database: "bonsai_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox,
extensions: [{Postgrex.Extensions.JSON, [library: Poison]}]
这是我的模特
defmodule Bonsai.Organization do
use Bonsai.Web, :model
schema "organizations" do
field :name, :string
field :currency, :string
field :tenant, :string
field :info, Bonsai.Json.Type, default: %{}
field :settings, :map, default: %{} #, :map#, Bonsai.Json.Type
timestamps
end
@required_fields ~w(name currency tenant)
@optional_fields ~w()
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
end
end
类型的定义在web/utils/json.ex
defmodule Bonsai.Json.Type do
@behaviour Ecto.Type
alias Bonsai.Json
def type, do: :json
def load({:ok, json}), do: {:ok, json}
def load(value), do: load(Poison.decode(value))
def dump(value), do: Poison.encode(value)
end
当我尝试测试时,我无法保存信息或设置地图
defmodule Bonsai.OrganizationTest do
use Bonsai.ModelCase
alias Bonsai.Organization
@valid_attrs %{currency: "USD", name: "Home", tenant: "bonsai",
settings: %{"last_save" => true},
info: %{"address" => "Samaipata", "mobile" => "73732677", "age" => 40}
}
test "Store json data" do
changeset = Organization.changeset(%Organization{}, @valid_attrs)
{:ok, org} = Bonsai.Repo.insert(changeset)
assert @valid_attrs.info() == org.info
end
end
答案 0 :(得分:6)
我不确定为什么它不适合你,但是:
确保你拥有最新的postgresql版本,json支持有点新的。
这对我有用,也许有帮助。
迁移文件
def change do
create table(:objects) do
add :drawing, :jsonb
timestamps
end
我也使用了json字段,但在我的模型中它是一个地图:
use .Web, :model
schema "objects" do
field :drawing, :map
timestamps
end