Hi, I have a problem which is not in adding or updating a record in database, just it returns in delete
, hence it works in update
and insert
correctly.
My migration:
create table(:blog_posts, primary_key: false) do
....
And my Blog author
def change do
create table(:blog_authors, primary_key: false) do
add(:id, :uuid, primary_key: true)
add(:post_id, references(:blog_posts, on_delete: :nothing, type: :uuid))
add(:user_id, references(:users, on_delete: :nothing, type: :uuid))
end
end
now in blog_authors
schema
schema "blog_authors" do
belongs_to :blog_posts, Post, foreign_key: :post_id, type: :binary_id
belongs_to :users, User, foreign_key: :user_id, type: :binary_id
end
And blog post schema
schema "blog_posts" do
...
has_many :blog_authors, BlogAuthor, foreign_key: :post_id, on_delete: :nothing
end
Finally blog_authors
changset
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:post_id, :user_id])
|> foreign_key_constraint(:post_id, message: "msg error")
|> foreign_key_constraint(:user_id, message: "msg error"))
|> unique_constraint(:post_id, name: :index_blog_authors_on_post_id_and_user_id, message: "msg error")
end
But I still have this error:
** (Ecto.ConstraintError) constraint error when attempting to delete struct:
* blog_authors_post_id_fkey (foreign_key_constraint)
After that, I even tested
|> foreign_key_constraint(:post_id, name: :blog_authors_post_id_fkey, message: "msg error")
But it does not show my message and returns the error. How to fix this error?
Before sending this post I saw many topics in my research, and they suggest that change
on_delete
to all but I want to force user deletes the depended on record before delete main record
Now I have to use rescue because of this problem
Delete function:
def delete_record(id) do
Repo.get(Post, id)
|> Repo.delete()
end
Thanks