I am inserting a model A that contains a foreign key for another model B.
defmodule MyApp.ModelA do use MyApp.Web, :model schema "model_a" do field :type, :string, null: false field :data, :string, null: false belongs_to :model_b, MyApp.ModelB timestamps() end @required_fields ~w(type data) @optional_fields ~w() @doc """ Builds a changeset based on the `struct` and `params`. """ def changeset(struct, params \\ %{}) do struct |> cast(params, @required_fields, @optional_fields) |> assoc_constraint(:model_b) end end
and model B:
defmodule MyApp.ModelB do use MyApp.Web, :model schema "model_b" do field :username, :string field :pass, :string has_many :model_a, MyApp.ModelA timestamps() end @required_fields ~w(username pass) @optional_fields ~w() @doc """ Builds a changeset based on the `struct` and `params`. """ def changeset(struct, params \\ %{}) do struct |> cast(params, @required_fields, @optional_fields) |> cast_assoc(:model_a) |> validate_required([]) end end
Model B exists since I can get it through Repo.all (ModelB).
Model Changing the parameter set has been tested successfully, and I can see the value of model_b_id when I print the model A changeet struct.
But when inserted, the link is not inserted. Although I see this when printing the model A change set, this field is completely absent in the MySQL log, it is not in the INSERT query.
I played a little, and if I make this reference field not be null in the MySQL table, then I get {"does not exist", []} for this foreign key field when pasted as Repo.insert (...) answer although model B exists in the database.