I'm new to using Elixir and would like to do a foreign key insertion in the bank (Postgres) via POST (it's 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 database, the relationship already exists, currency_id is a foreign key in the "wallets" table.
When I do POST, it returns this error, showing the entire struct with the fields, and with the primary key missing message:
struct
%MeuProjeto.Carteiras.Carteira{...}
is missing primary key value
I still can not figure out how to put this primary key, I found that only using has_one and belongs_to it already made the association. I've also put in the validate_required field with the foreign key, but I read that this could generate security holes, and the error remained the same.
EDIT Ok, after searching I understood what the problem was.
First that I do not need this has_one / belongs_to relationship if I will not use the data from my table that the foreign key directs.
And after that I was missing the foreign_key_constraint () function in my Wallet schema.
The final code was thus:
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 just removed the has_one: currency, MyProject.Moedas.Moeda