Ruby on rails Rails ActiveRecord::InvalidForeignKey在ArticlesController中#销毁

Ruby on rails Rails ActiveRecord::InvalidForeignKey在ArticlesController中#销毁,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我正在创建一个博客应用程序,每次我试图删除一篇有评论的文章时都会出现这个错误。我怎样才能修好它 让我知道发布什么代码,我会更新问题 物品管理员: ActiveRecord::InvalidForeignKey in ArticlesController#destroy SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "articles" WHERE "articles"."id" = ? 为了避

我正在创建一个博客应用程序,每次我试图删除一篇有评论的文章时都会出现这个错误。我怎样才能修好它

让我知道发布什么代码,我会更新问题

物品管理员:

ActiveRecord::InvalidForeignKey in ArticlesController#destroy

SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "articles" WHERE "articles"."id" = ?

为了避免这个问题,您可以在
文章
模型中定义
dependent::delete_all
,这样每个相关的
注释也会被删除,如下所示:

ArgumentError in ArticlesController#destroy

Unknown key: :dependant. Valid keys are: :class_name, :anonymous_class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type, :index_errors
类文章
使用
dependent::delete\u all
不使用验证,因此它直接删除记录而不正确验证。如果希望安全验证记录,请使用
dependent::destroy

class Article < ApplicationRecord
  has_many :comments, dependent: :delete_all
end
类文章
除其他正确答案外:

在许多情况下,您实际上可能希望保留关联的模型,只需删除关联表中的外键:

class Article < ApplicationRecord
  has_many :comments, dependent: :destroy
end
我没有测试代码,这有点离题,但我希望它能有所帮助


干杯

你说的验证是什么意思?记录将被删除,你需要验证吗?我找到了这个
ArgumentError in ArticlesController#destroy

Unknown key: :dependant. Valid keys are: :class_name, :anonymous_class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type, :index_errors
class Article < ApplicationRecord
  has_many :comments, dependent: :delete_all
end
class Article < ApplicationRecord
  has_many :comments, dependent: :destroy
end
class Article < ApplicationRecord
  has_many :comments, dependent: :nullify
end
class Article < ApplicationRecord
  act_as_paranoid

  # Not accurate, but here is approximatively what the gem does :
  # default_scope where(deleted_at: nil)

  has_many :comments, dependent: :delete_all # or :destroy if you have callbacks in Comment model

  def self.clean
    only_deleted.where('destroyed_at < ?', Date.today - 6.month).destroy_fully!
  end
end
# Whenever: schedule.rb
every 1.day, at: '4:30 am' do
  runner "Article.clean"
end