Saving a foreign key with changeset gives xxx_id doesnt exist

inserting

ā€˜#Ecto.Changeset<action: nil,
changes: %{account_id: 1},
errors: [], data: #AcApi.Acc.Posting<>, valid?: true>ā€™

gives

#Ecto.Changeset<action: :insert, changes: %{account_id: 1, errors: [account_id: {"does not exist", []}], data: #AcApi.Acc.Posting<>, valid?: false>}

although im able to save without a changeset and the account does exist.

Can you show us the schema and the code you are using?

  schema "postings" do
    belongs_to :account, Account
    timestamps()
  end


  def create_changeset(posting, attrs) do
    posting
    |> cast(attrs, [])
    |> validate_required([])
    |>foreign_key_constraint(:account_id)
  end

def create_posting(attrs) do
    change(%Posting{},  %{account_id: attrs["account_id"]})
    |> Posting.create_changeset(attrs)
    |> Repo.insert()
end

schema "accounts" do
   has_many :postings, Posting
   timestamps()
end

attrs = %{"account_id"=>1}

using

Repo.insert! %Posting{
account_id: 1

}

however works.

It turns out i didnt have the right seed data in my test database:neutral_face:

1 Like

You should mark as solved then. :slight_smile:

1 Like