产品线项目变量模式

时间:2017-09-12 13:11:03

标签: elixir phoenix-framework

我的最终目标是,当管理员创建产品时,他们可以选择最终用户在添加到购物车时可供选择的变体,有时是多个选择,有时只有一个选择。例如,仅一种尺寸,小型,中型等

这是我的产品架构:

schema "products" do
  field :category, :string
  field :description, :string
  field :image, Qcrafts.Images.Type
  field :name, :string
  field :price, :decimal
  field :slug, ProductSlug.Type

  timestamps()
end

我的line_item

embedded_schema do
  field :product_id, :integer
  field :image, Qcrafts.Images.Type
  field :product_name, :string
  field :quantity, :integer
  field :unit_price, :decimal
  field :total, :decimal
  field :delete, :boolean, virtual: true
end

我最需要哪种关系,哪种关系最适合在模板上处理?

1 个答案:

答案 0 :(得分:0)

如果不改变你的东西,我想我会做这样的事情:

defmodule Product do
  use Ecto.Schema

  schema "products" do
    field :category, :string
    field :description, :string
    field :name, :string
    field :slug, ProductSlug.Type
    has_many :variants, ProductVariant
    belongs_to :default_variant, ProductVariant

    timestamps()
  end
end
defmodule ProductVariant do
  use Ecto.Schema

  schema "product_variants" do
    field :product_id, :id
    field :description, :string
    field :image, Qcrafts.Images.Type
    field :name, :string
    field :price, :decimal
    field :slug, ProductSlug.Type

    timestamps()
  end
end
defmodule LineItem do
  use Ecto.Schema

  embedded_schema do
    field :product_variant_id, :id
    field :image, Qcrafts.Images.Type
    field :product_name, :string
    field :quantity, :integer
    field :unit_price, :decimal
    field :total, :decimal
    field :delete, :boolean, virtual: true
  end
end

在模板中,您可以执行以下操作:(确保预加载)

表单示例:

multiple_select(form, :variants, Enum.map(@product.variants, &({&1.name, &1.id})),
                selected: Enum.map(@product.variants, &(&1.id)))

或列表示例:

<ul>
  <%= for variant <- @product.variants do %>
    <li><%= variant.name %></li>
  <% end %>
</ul>