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 (https://hexdocs.pm/ecto/Ecto.Changeset.html#validate_exclusion/4). 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: