外键约束,博客文章,acts_as_votable

时间:2018-09-06 16:57:46

标签: ruby-on-rails blogs sql-delete acts-as-votable

因此,我安装了gemacts_as_votable或它的任何名称。很棒的投票系统。但是,在我的管理员中,当我删除博客文章时,我得到了一个sqlite外键约束失败的错误消息。我知道这与数据库表有关,如果您尝试删除一个表上具有另一个表上的外键的记录,这会导致问题,除非为外键定义了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:外键约束失败:在“ home_blogs”中删除“ home_blogs”。“ id” =?

1 个答案:

答案 0 :(得分:0)

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

... 

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

...