如何在Phoenix中处理嵌入式架构?

时间:2017-04-21 07:39:32

标签: mongodb elixir phoenix-framework ecto

假设我有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)验证两者后如何获得最终变更集?

1 个答案:

答案 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