2017-07-03 69 views
0

我正在做一個Ruby on Rails課程,我正在試圖刪除一個投資組合項目,但它給了我一個錯誤。這是錯誤。如何刪除導軌中的項目?


ActiveRecord::InvalidForeignKey in PortfoliosController#destroy


PG::ForeignKeyViolation: ERROR: update or delete on table "portfolios" violates foreign key constraint "fk_rails_cc5ab4a1c3" on table "technologies" DETAIL: Key (id)=(12) is still referenced from table "technologies". : DELETE FROM "portfolios" WHERE "portfolios"."id" = $1


Extracted source (around line #52):


50 
51 # Destroy/delete the record 
52 @portfolio_item.destroy 
53 
54 # Redirect 
55 respond_to do |format|` 

Rails.root: /home/ubuntu/workspace/DevcampPortfolio/ClonedRepo/Devcamp-Portfolio


Application Trace | Framework Trace | Full Trace app/controllers/portfolios_controller.rb:52:in 'destroy'


Request

Parameters:

{"_method"=>"delete", "authenticity_token"=>"3fGuZqFrTblpS7aQGpfszjN24lSxu6SAr5/JRlLc0RDupDZ7BJKJr6kPnEYHa0/BR7rmTPnN+/i5Ptjb3wCLtw==", "id"=>"12"}


Response

Headers:

None


the code for the place I am in the course

my code


我該如何改變以解決它?

回答

1

您需要將依賴關係::destroy添加到投資組合模型的has_many關係中。

has_many:technologies,dependent::destroy 這樣做會使得當你銷燬一個投資組合時,它會破壞屬於投資組合的技術。

如果您想要保留技術,您需要更改它們之間的關係,或者允許它們成爲無父母,並將before_destroy操作掛接到投資組合模型。

+0

我試圖做你說的,但我無法弄清楚。你能告訴我什麼代碼與依賴:: destroy部分?我是新手,我不太瞭解。 –

+0

在你的portfolio.rb文件中,寫下「has_many technologies,dependent :: destroy」,當你銷燬它時,它會殺死屬於該組合的技術表中的元素 – Maxence

+0

Postgres doesn'就像你殺了一位父母,並讓孩子提及那位父母。位於技術領域的投資組合foreign_key則無所作爲。我認爲與其他數據庫不同,你可以刪除父對象,而不會引用它。 – Maxence