0

所以我安装了 gemacts_as_votable 或任何它的名字。很棒的小投票系统。但是,在我的管理员中,当我删除博客文章时,我收到一个外键约束失败的 sqlite 错误消息。我知道这与 db 表有关,如果您尝试删除一个表上的记录,该表在另一个表上具有外键,则会导致问题,除非为外键定义了 on_delete: :cascade 等。我是不知道如何为acts_as_votable gem 做到这一点。有人知道吗?谢谢!

博客模型:

class HomeBlog < ApplicationRecord
  mount_uploader :image, ImageUploader
  has_many :hashtaggings
  has_many :hashtags, through: :hashtaggings

  acts_as_votable

  def all_hashes=(names)
    self.hashtags = names.split(",").map do |name|
      Hashtag.where(name: name.strip).first_or_create!
    end
  end

  def all_hashes
    self.hashtags.map(&:name).join(", ")
  end
end

博客控制器:

class Admin::HomeBlogsController < Admin::AdminController

  before_action :set_home_blog, only: [:show, :destroy]


  def destroy
    @admin_home_blog.destroy!
    respond_to do |format|
      format.html { redirect_to admin_home_blogs_path, notice: 'Blog post was successfully deleted.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_home_blog
      @admin_home_blog = Admin::HomeBlog.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def admin_home_blog_params
      params.require(:home_blog).permit(:name, :entry, :image, :all_hashes)
    end
  end

页面视图:

<h3 id="blog-index-title">Blog Posts</h3>


<span class="pagination"><%= will_paginate @admin_home_blogs %></span>
<% @admin_home_blogs.each do |h| %>

<div id="admin-blog-index">
  <%= link_to h.name, h %> | <button type="button"><%= link_to "delete", admin_home_blog_path(h), :style=>'color:white', method: :delete, data: {confirm: "Are you sure?"}%></button>
</div><br />
<% end %>

错误信息:

SQLite3::ConstraintException: FOREIGN KEY 约束失败:DELETE FROM "home_blogs" WHERE "home_blogs"."id" = ?

4

1 回答 1

0

我相信这个问题是您需要在删除帖子时销毁依赖帖子的记录。

... 

has_many :hashtaggings, dependent: :destroy
has_many :hashtags, through: :hashtaggings, dependent: :destroy

...
于 2018-09-06T19:28:05.477 回答