Problem with foreign key insertion in Postgres bank - Elixir/Phoenix

Asked

Viewed 47 times

1

I am new in the use of Elixir and would like to make an insertion with foreign key in the bank (Postgres), via POST (is a JSON)

below my modules

defmodule MeuProjeto.Carteiras.Carteira do
  use Ecto.Schema
  import Ecto.Changeset


  schema "carteiras" do
    field :campo_1, :string
    field :campo_2, :integer
    field :moedas_id, :id
    has_one :moeda, MeuProjeto.Moedas.Moeda

    timestamps()
  end

  @doc false
  def changeset(carteira, attrs) do
    carteira
    |> cast(attrs, [:campo_1, :campo_2])
    |> validate_required([:campo_1, :campo_2])
  end
end

and

defmodule MeuProjeto.Moedas.Moeda do
  use Ecto.Schema
  import Ecto.Changeset


  schema "moedas" do
    field :nome, :string
    belongs_to :carteira, MeuProjeto.Carteiras.Carteira

    timestamps()
  end

  @doc false
  def changeset(moeda, attrs) do
    moeda
    |> cast(attrs, [:nome])
    |> validate_required([:nome])
  end
end

in the bank, the relationship already exists, moeda_id is a foreign key in the table "portfolios".

When I do the POST, returns this error, showing all the struct with the fields, and with the primary key missing message:

struct %MeuProjeto.Carteiras.Carteira{...} is Missing Primary key value

I still could not understand how to put this primary key, I found that only using has_one and belongs_to he already made the association. I also already put inside the validate_required field with the foreign key, but read that this can generate security holes, and the error remained the same.

EDIT Okay, after researching I understood what the problem was.

First I don’t need this has_one/belongs_to relation if I’m not going to use the data from my table that the foreign key directs.

And after I missed entering the foreign_key_constraint() function in my Wallet schema.

That’s the final code:

defmodule MeuProjeto.Carteiras.Carteira do
  use Ecto.Schema
  import Ecto.Changeset


  schema "carteiras" do
    field :campo_1, :string
    field :campo_2, :integer
    field :moedas_id, :id

    timestamps()
  end

  @doc false
  def changeset(carteira, attrs) do
    carteira
    |> cast(attrs, [:campo_1, :campo_2, :moedas_id])
    |> foreign_key_constraint(:moedas_id)
    |> validate_required([:campo_1, :campo_2, :moedas_id])
  end
end

In the Currency schema, I only removed the line has_one : coin, Mycoin coin.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.