2016-04-07 67 views
1

我有一個phoenix應用程序,帖子屬於用戶。如果用戶被刪除,確保屬於用戶的帖子被刪除

當我試圖刪除誰擁有的帖子,我發現了以下錯誤用戶:

Ecto.ConstraintError at DELETE /users/2 
constraint error when attempting to delete model: 

    * foreign_key: posts_user_id_fkey 

我假定這個錯誤意味着它不會刪除用戶,因爲有現有職位屬於該用戶。

如果/當用戶被刪除時如何刪除用戶帖子?

回答

5

我做了一些更多的搜索,我想我找到了答案,我的問題:

我已經添加了以下

schema "users" do 
    ... 
    has_many :posts, MyApp.Post, on_delete: :delete_all 
    ... 
end 

請評論,如果這不是正確的方式做這個或者如果有更好的方法。

+1

是的,這就是答案。在這裏你有方便的鏈接:http://blog.plataformatec.com.br/2015/08/working-with-ecto-associations-and-embeds/ https://hexdocs.pm/ecto/Ecto.Schema.html – tkowal

相關問題