Can we restrict the deletion of a user from database based on the email address?

Can we restrict the deletion of a user from database based on his email address in Repo.delete!(changeset) condition in elixir and phoenix web development

This is right now the code which I am using. I want to restrict the deletion of two users from database during deletion:-

def delete(conn, _params, current_admin) do

    changeset = AdminUser.common_changeset(conn.assigns.admin_user, %{}, whodoneit(current_admin))

    Repo.delete!(changeset)

    msg = gettext("%{name} deleted successfully", name: gettext("Administrator"))

    conn
    |> put_flash(:success, msg)
    |> redirect(to: Routes.admin_admin_user_path(conn, :index))

end


I want to restrict the deletion of users with email ids say 'test1@gmail.com' and 'test2@gmail.com'. But I am not sure how to use this in changeset.

Of course You canā€¦ just add a condition before Repo.delete! to check the email.

As your changeset is built from conn.assigns.admin_user, You might check here too, otherwise, check changeset.data.

Thanks for respondingā€¦
Here is my query condition
query = Repo.all(from u in AdminUser, where: u.email == ā€œtest1@gmail.comā€ or u.email == ā€œtest2@gmail.comā€).

How to check the email id in the changeset?

I do not understand why You need this queryā€¦

You might add

IO.inspect changeset

to see what is inside your changeset.

Sorry if I could not make it clear.
My aim is -

Repo.delete!(changeset) should not delete the users with email id ā€˜test1@gmail.comā€™ or ā€˜test2@gmail.comā€™

If you can guide me how to achieve this, it would be very helpful.

I am sorry but I donā€™t think itā€™s possible. Before Repo.delete yes, but not withā€¦

The deletion wonā€™t happen if the changeset isnā€™t valid, so make sure either of those emails renders it invalid (Ecto.Changeset ā€” Ecto v3.11.1). Or is there something more to it Iā€™m missing?

3 Likes

Oh yes, like this it is possible :slight_smile:

What you want is achievable and is in the documentation (as already linked).

Let us know how you solved it.

The requirement got changed and now I do not want to achieve the above. So want to close this issue.

As You selected chat/discussion, this topic is not closableā€¦

I can change the category, and close it for You if needed.

Update: Doneā€¦

Thanks Please close it.

Please read. :slight_smile: