【问题标题】:elixir ecto - embed_one with multiple schemaelixir ecto - 具有多个模式的 embed_one
【发布时间】:2021-10-09 02:52:17
【问题描述】:

我有一个item 表,我想拥有多个embedded schema,例如:

  schema "items" do
    field :name, :string
    field :type, :string

    #embed_one with :either, I found this somewhere online but can't get the doc anywhere.
    embeds_one :details, either: [ Product, Service], on_replace: :update

  @doc false
  def changeset(item, attrs) do
    item
    |> cast(attrs, [:name, :type, :description, :publish, :user_id])
    |> details_by_type(attrs[:type], :details)
  end

  #psuedo code of cast_embed
  defp details_by_type(item, type, details) do
    case type do
      :product -> item |> #cast_embed of :details to Product
      :service -> item |> #cast_embed of :details to Service
    end
  end

基本上,我想要一个 details 字段(:map),它根据项目的类型保留不同的嵌入模式。但我无法让它工作。我不断收到这样的错误:

(ArgumentError) 你试图在 [或者: [OkBackend.Items.Task,OkBackend.Items.Product, OkBackend.Items.Service],on_replace: :update]。模块(第一个 apply) 的参数必须始终是一个原子

这样做的正确方法是什么?

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

    看起来这个包就是你要找的,这是文档中的一个例子:

    defmodule MyApp.Reminder do
      use Ecto.Schema
      import Ecto.Changeset
      import PolymorphicEmbed, only: [cast_polymorphic_embed: 3]
    
      schema "reminders" do
        field :date, :utc_datetime
        field :text, :string
    
        field :channel, PolymorphicEmbed,
          types: [
            sms: MyApp.Channel.SMS,
            email: [module: MyApp.Channel.Email, identify_by_fields: [:address, :confirmed]]
          ],
          on_type_not_found: :raise,
          on_replace: :update
      end
    
      def changeset(struct, values) do
        struct
        |> cast(values, [:date, :text])
        |> cast_polymorphic_embed(:channel, required: true)
        |> validate_required(:date)
      end
    end
    

    https://hexdocs.pm/polymorphic_embed/readme.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 2016-10-26
      • 2023-03-05
      • 2017-01-12
      • 2018-06-24
      相关资源
      最近更新 更多