0

當我嘗試在ROR中的非常簡單的應用程序上運行測試時出現錯誤。我在網上服用一個療程,我有兩個表這個非常簡單的數據庫:posts(與titlebody)和comments(與ForeignKey的:post_idbody當我運行rake test我得到以下錯誤:在Ruby on Rails中運行Rake測試時出錯

Error: PostsControllerTest#test_should_destroy_post: 
ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN 
KEY constraint failed: DELETE FROM "posts" WHERE "posts"."id" = ? 
    app/controllers/posts_controller.rb:57:in `destroy' 
    test/controllers/posts_controller_test.rb:43:in `block (2 levels) in <class:PostsControllerTest>' 
    test/controllers/posts_controller_test.rb:42:in `block in <class:PostsControllerTest>' 


bin/rails test test/controllers/posts_controller_test.rb:41 

.... 

Finished in 12.539965s, 1.1164 runs/s, 1.2759 assertions/s. 14 runs, 
16 assertions, 0 failures, 1 errors, 0 skips` 

任何幫助,將不勝感激。謝謝你。當你在一個表,它的主鍵在另一表中被引用刪除行發生

+0

https://stackoverflow.com/questions/15443913/sqlite3-foreign-key-constraint-failed –

回答

0

此錯誤。您可以包括ON DELETE CASCADE在你的外鍵定義(在此定義,其中主鍵被另一個表引用),或添加另一個表刪除語句刪除引用主鍵的行,然後再執行您當前正在執行的刪除語句。

0

添加到您的Post型號:

has_many :comments, dependent: :destroy 

這將破壞相關的評論時,你會摧毀你的Post模型。所以你不會得到ConstraintException

你可以找到更多關於Rails協會here的信息。