ruby-on-rails – 无法删除或更新父行:外键约束失败 – 删除博
发布时间:2020-12-17 02:56:01 所属栏目:百科 来源:网络整理
导读:我已经检查了类似问题的其他答案,我想我明白他们的意思,但我不知道如何解决它. 我在尝试删除我网站上的博客中的帖子时收到此错误消息.我已经尝试从Rails控制台获得类似的消息. ActiveRecord::StatementInvalid in PostsController#destroyMysql2::Error: Can
我已经检查了类似问题的其他答案,我想我明白他们的意思,但我不知道如何解决它.
我在尝试删除我网站上的博客中的帖子时收到此错误消息.我已经尝试从Rails控制台获得类似的消息. ActiveRecord::StatementInvalid in PostsController#destroy Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails (`mysite_development`.`comments`,CONSTRAINT `fk_rails_2fd19c0db7` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`)): DELETE FROM `posts` WHERE `posts`.`id` = 3 posts_controller.rb class PostsController < ApplicationController before_filter :authenticate,:except => [ :index,:show ] before_action :set_post,only: [:show,:edit,:update,:destroy] # GET /posts # GET /posts.json def index @posts = Post.all end # GET /posts/1 # GET /posts/1.json def show end # GET /posts/new def new @post = Post.new end # GET /posts/1/edit def edit end # POST /posts # POST /posts.json def create @post = Post.new(post_params) respond_to do |format| if @post.save format.html { redirect_to @post,notice: 'Post was successfully created.' } format.json { render :show,status: :created,location: @post } else format.html { render :new } format.json { render json: @post.errors,status: :unprocessable_entity } end end end # PATCH/PUT /posts/1 # PATCH/PUT /posts/1.json def update respond_to do |format| if @post.update(post_params) format.html { redirect_to @post,notice: 'Post was successfully updated.' } format.json { render :show,status: :ok,location: @post } else format.html { render :edit } format.json { render json: @post.errors,status: :unprocessable_entity } end end end # DELETE /posts/1 # DELETE /posts/1.json def destroy @post.destroy respond_to do |format| format.html { redirect_to posts_url,notice: 'Post was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_post @post = Post.find(params[:id]) end # Never trust parameters from the scary internet,only allow the white list through. def post_params params.require(:post).permit(:title,:body) end end edit.html.erb <h1>Editing Post</h1> <%= render 'form' %> <%= link_to 'Show',@post %> | <%= link_to 'Back',posts_path %> <%= link_to 'Delete',@post,method: :delete %> _form.html.erb <%= simple_form_for(@post) do |f| %> <%= f.error_notification %> <div class="form-inputs"> <%= f.input :title %> <%= f.input :body %> </div> <div class="form-actions"> <%= f.button :submit %> </div> <% end %> 有任何想法吗? 解决方法
它与您的控制器代码无关.您在架构中添加了一个
database foreign constraing,它禁止在有关联记录时删除对象.
在这种情况下,您试图删除附有评论的帖子.您需要更改架构并更新外键定义,以指示数据库在这种情况下要执行的操作.具体来说,您可能希望删除级联上的关联记录. 理论上,您可以使用Post模型中的dependent :: destroy Rails设置来删除级联中的注释,但是因为您有一个外键,所以这不是一个好主意.如果在这种情况下将任务委托给数据库,它会更快更好. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |