假设我有user
模型,请关注
schema "users" do
field :user_name, :string
field :password, :string
end
和address
模型如下
schema "address" do
field :line1, :string
field :country, :string
end
我使用mongo db作为数据库,所以我想要json格式,如关注
{_id:" dfd",user_name:" $$$$",密码:" xxx",地址:{line1:" line1",country:" india" }}
1)如何创建和验证变更集,其中user
模式中的用户名和address
模型中的国家/地区是必填字段?
2)验证两者后如何获得最终变更集?
答案 0 :(得分:1)
假设mongo适配器与postgresql jsonb列类似:
defmodule User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :user_name, :string
field :password, :string
embeds_one :address, Address
end
def changeset(model, params \\ %{}) do
model
|> cast(params, [:user_name, :password]
|> cast_embed(:address)
|> validate_required(:user_name, :password, :address)
end
end
defmodule Address do
use Ecto.Schema
import Ecto.Changeset
@primary_key false
embedded_schema do
field :line1, :string
field :country, :string
end
def changeset(model, params \\ %{}) do
model
|> cast(params, [:line1, :country])
|> validate_required([:line1, :country])
end
end