Ассоциация Феникс Эликсир - PullRequest
0 голосов
/ 20 января 2019

У меня есть вопрос об ассоциации в Phoenix Elixir, это происходит при вставке нового клиента, возникает несколько ассоциаций между ними, схема Doc получает «customer_id», а также схему контактов и долгов, все это работает.Но также в этой транзакции я хочу связать «doc_id» схемы Doc, созданной со схемой Debt, у меня это не работает.

Схема клиента

 defmodule App.Customers.Customer do
  use Ecto.Schema
  import Ecto.Changeset
  alias App.Customers.{ Contact, Doc, Debt }
  alias App.Collections.Collection

  schema "customers" do
    field :codLegal, :string
    field :businessName, :string
    field :fantasyName, :string
    has_many :contacts, Contact
    has_many :docs, Doc
    has_one :collection, Collection 
    has_many :debts, Debt

    timestamps()
  end

  def changeset(customer, attrs \\ %{}) do
    customer
    |> cast(attrs, [:codLegal, :businessName, :fantasyName])
    |> validate_required([:codLegal, :businessName, :fantasyName])
    |> unique_constraint(:codLegal)
    |> cast_assoc(:docs, with: &App.Customers.Doc.changeset/2)
    |> cast_assoc(:contacts, with: &App.Customers.Contact.changeset/2)
    |> cast_assoc(:debts, with: &App.Customers.Debt.changeset/2)
  end
end

Схема документа

defmodule App.Customers.Doc do
  use Ecto.Schema
  import Ecto.Changeset
  alias App.Customers.{ Doc, Customer, Debt }
  alias App.Collections.Collection

  schema "docs" do
    field :number, :string
    field :startdate, :date
    field :endate, :date
    field :type, :string
    belongs_to :customer, Customer
    many_to_many :collections, Collection, join_through: "collections_docs"
    has_one :debt, Debt

    timestamps()
  end

  @doc false
  def changeset(doc, attrs) do
    doc
    |> cast(attrs, [:type, :number, :startdate, :endate])
    |> validate_required([:type, :number, :startdate, :endate])
    |> unique_constraint(:number)
    |> cast_assoc(:debt, with: &App.Customers.Debt.changeset/2)
  end
end

Схема задолженности

defmodule App.Customers.Debt do
  use Ecto.Schema
  import Ecto.Changeset
  alias App.Customers.{ Customer, Doc }


  schema "debts" do
    field :credit, :integer
    field :debit, :integer
    belongs_to :doc, Doc
    belongs_to :customer, Customer

    timestamps()
  end

  @doc false
  def changeset(debt, attrs) do
    debt
    |> cast(attrs, [:debit, :credit])
    |> validate_required([:debit])
  end
end
...