![](/img/trans.png)
[英]Rails: undefined method `user' for nil:NilClass (NoMethodError in ArticlesController#destroy)
[英]Rails ActiveRecord::InvalidForeignKey in ArticlesController#destroy
ActiveRecord::InvalidForeignKey in ArticlesController#destroy
SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "articles" WHERE "articles"."id" = ?
我正在創建一個博客應用程序,每次嘗試刪除其中有評論的文章時,都會出現此錯誤。 我該如何解決?
讓我知道要發布的代碼,然后我將更新問題。
文章控制者:
class ArticlesController < ApplicationController
def new
@article = Article.new
end
def index
#@articles = Article.all
@articles = Article.paginate(:page => params[:page], :per_page => 10)
end
def show
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
end
private
def article_params
params.require(:article).permit(:title, :text, :datee)
end
文章模型:
class Article < ApplicationRecord
has_many :comments
has_many :photos
end
評論模型:
class Comment < ApplicationRecord
belongs_to :article
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
使用dependent: :delete_all
不使用驗證,因此它直接刪除記錄而沒有正確驗證。 如果希望安全地驗證記錄,請使用dependent: :destroy
。
class Article < ApplicationRecord
has_many :comments, dependent: :destroy
end
為避免此問題,您可以在Article
模型中定義dependent: :delete_all
,以便也刪除所有相關的Comment
,如下所示:
class Article < ApplicationRecord
has_many :comments, dependent: :delete_all
end
除其他正確答案外:
在許多情況下,您實際上可能想要保留關聯的模型,而只是刪除關聯表中的外鍵:
class Article < ApplicationRecord
has_many :comments, dependent: :nullify
end
例如,如果要構建博客模塊,則法律有義務在實際刪除之前將用戶評論存檔一段時間。 因此,您想遵守它,我也建議您使用軟刪除系統,例如paranoia或act_as_paranoid :
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
這樣,當您刪除文章時,評論不會被破壞,文章本身也不會被破壞。 然后,您可以設置一些cron任務( 無論何時 )或delay_job,以在經過法定保留時間后執行實際的刪除操作:
# Whenever: schedule.rb
every 1.day, at: '4:30 am' do
runner "Article.clean"
end
我沒有測試代碼,這有點偏離主題,但我希望它能對您有所幫助。
干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.