Create a relation has_many

Hello

I have two schemas, and I am trying to create a relation has_many

 defmodule Example.Accounts.User do
  use Ecto.Schema
  import Ecto.Changeset
  alias Example.Accounts.User


  schema "users" do
    field :identification, :integer
    field :name, :string
    has_many :properties, Example.Properties.Property
    timestamps()
  end

  @doc false
  def changeset(%User{} = user, attrs) do
    user
    |> cast(attrs, [:identification, :name])
    |> validate_required([:identification, :name])
  end
end

And

defmodule Example.Properties.Property do
  use Ecto.Schema
  import Ecto.Changeset
  alias Example.Properties.Property


  schema "properties" do
    field :n_property, :integer
    belongs_to :user, Example.Accounts.User

    timestamps()
  end

  @doc false
  def changeset(%Property{} = property, attrs) do
    property
    |> cast(attrs, [:n_property])
    |> validate_required([:n_property])
  end
end

After running ecto.create and ecto.migrate the result on my PostgresDB is the following

 CREATE TABLE public.properties
(
    id bigint NOT NULL DEFAULT nextval('properties_id_seq'::regclass),
    n_property integer,
    inserted_at timestamp without time zone NOT NULL,
    updated_at timestamp without time zone NOT NULL,
    CONSTRAINT properties_pkey PRIMARY KEY (id)
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;

ALTER TABLE public.properties
OWNER to postgres;

And I don’t understand, Why doesn’t it create a foreign_key?

@YuelWolf: If I well understand your problem then you need to call &references/2 in your migration file.

1 Like

Thank you :smiley: