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

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
New
Tee
can someone please explain to me how Enum.reduce works with maps
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
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New

Other popular topics Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
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

We're in Beta

About us Mission Statement