如何解决PG::ForeignKeyViolation:错误:更新或删除表,我不知道为什么
我联系您是因为我有一个相当重要的问题。尽管我对 stackoverflow 或其他地方进行了研究,但经过大量测试和大量修补后,我仍无法纠正。
我通过制作一个网站来练习,您可以在其中列出我称之为“八卦”的秘密。
但是当我想删除“八卦”时
据我所知,是我的表之间的关系导致了问题。因此,我将这些表格的代码附在问题中:
class Tag < ApplicationRecord
has_many :gossips,through: :tag_join_gossip,dependent: :destroy
validates :title,presence: true
end
class TagJoinGossip < ApplicationRecord
belongs_to :gossip
belongs_to :tag,optional: true
end
class Gossip < ApplicationRecord
belongs_to :user,optional: true
has_many :likes
has_many :tags,through: :tag_join_gossip
has_many :comments
validates :title,presence: true,length: {minimum: 3,maximum: 14}
validates :content,length: {minimum: 1}
end
我的控制器:
class GossipController < ApplicationController
before_action :authenticate_user
def index
@id = params[:id]
@gossips = Gossip.all
end
def show
@id= params[:id]
@gossip = Gossip.find(params[:id])
@comments = Gossip.find(params[:id]).comments
@comment = Comment.new(content: params['content'],gossip_id: 1,gossip_id: @gossip,user_id: 1)
end
def new
@gossip = Gossip.new
end
def create
@gossip = Gossip.new(title: params['title'],content: params['content'])
@gossip.user = User.find_by(id: session[:user_id])
if @gossip.save
flash[:success] = "Gossip bien créé!"
redirect_to welcome_index_path
else
flash[:danger] = "Nous n'avons pas réussi à créer le potin pour la (ou les) raison(s) suivante(s) "
render new_gossip_path
end
end
def edit
@gossip = Gossip.find(params[:id])
end
def update
@gossip = Gossip.find(params[:id])
gossip_params = params.require(:gossip).permit(:title,:content)
if @gossip.update(gossip_params)
flash[:success] = "Gossip bien modifié !"
redirect_to welcome_index_path
else
render :edit
flash[:danger] = "Nous n'avons pas réussi à modifier le potin,le titre doit faire 3 lettres minimum et vous devez remplir le contenu."
end
end
def destroy
@gossip = Gossip.find(params[:id])
@gossip.destroy
redirect_to welcome_index_path
end
end
private
def authenticate_user
unless current_user
flash[:danger] = "Veuillez vous connecter."
redirect_to new_session_path
end
end
也许还有其他感兴趣的文件,所以我把我的项目的 github 放在这里:https://github.com/MC4517/Projet-THP-GOSSIP-J1
我已经玩了一整天了,我开始失去理智了哈哈。
非常感谢那些敢于解决我的问题的人,尽管我认为这对你们中的大部分人来说一定很容易!
解决方法
您有一条记录,其外键 (TagJoinGossip) 引用了您要销毁的记录 (Gossip)。将dependent::destroy 添加到has_many 关联应该可以解决它。
Class Gossip < ApplicationRecord
has_many :tags,through: :tag_join_gossip,dependent: :destroy
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。