carlosarli

carlosarli

Constraint error when attempting to delete struct

Hello everyone,
I have the following models and changesets for users and addresses:
user.ex

schema "users" do
        field :title, :string
        field :f_name, :string
        field :l_name, :string
        field :DOB, :date
        field :email, :string
        field :username, :string
        field :password, :string, virtual: true
        field :password_confirmation, :string, virtual: true
        field :password_hash, :string
        field :image, Assistant.Image.Type

        #associations
        has_one :addresses, Assistant.Web.Address
        has_many :appointment, Assistant.Web.Appointment
        belongs_to :role, Assistant.Web.Role

        timestamps()
    end

    #checks the changeset of the controller to see whether the input matches the rules I set here
    def changeset(model, params \\ :invalid) do
        model
        |> cast(params, ~w(title f_name l_name DOB email username role_id))
        |> cast_attachments(params, [:image])
        |> validate_required([:title, :f_name, :l_name, :DOB, :email, :username, :role_id, :image])
        |> validate_length(:username, min: 2, max: 20)
        |> unique_constraint(:username)
        |> assoc_constraint(:role)
        |> cast_assoc(:addresses, required: true)
    end

Address.ex

schema "addresses" do
        field :house_n, :integer
        field :address_1, :string
        field :address_2, :string
        field :post_code, :string
        field :city, :string
        field :county, :string
        field :country, :string

        belongs_to :user, Assistant.Web.User, foreign_key: :user_id

        timestamps()
    end

      @doc """
      Builds a changeset based on the `struct` and `params`.
      """
    def changeset(struct, params \\ %{}) do
        struct
        |> cast(params, [:house_n, :address_1, :address_2, :post_code, :city, :county, :country])
        |> validate_required([:house_n, :address_1, :address_2, :post_code, :city, :county, :country])
    end

When I try to delete a new user I have created it gives me this error:
constraint error when attempting to delete struct:

  • foreign_key: addresses_user_id_fkey

I have searched through the forum and on stack overflow and the solution seems to be to add the foreign_key_constraint(), but I am not exactly clear on how to go on about it as I have tried following the suggestions, but so far I keep getting the same error. Has it got anything to do with the cast_assoc()? I’ve got that from the book programming phoenix but online I found varying opinions on it so I thought maybe that could be the issue.

Thank you for your help :slight_smile:

Most Liked

kokolegorille

kokolegorille

Maybe You could set the on_delete option between user and its addresses association.

By default, it will do nothing… Thus I think it is why You get this error.

For this to work, You could look at

https://hexdocs.pm/ecto/Ecto.Migration.html#references/2

and

This would be in your addresses migration

add :user_id, references("users"), on_delete: :delete_all

and in the schema

has_one :addresses, Assistant.Web.Address, on_delete: :delete_all

It is not tested, but it might help…

Where Next?

Popular in Questions Top

lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New

We're in Beta

About us Mission Statement