簡體   English   中英

外鍵約束,博客文章,acts_as_votable

[英]foreign key constraint, blog post, acts_as_votable

因此,我安裝了gemact_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” =?

我相信這個問題是您刪除帖子時需要銷毀依賴該帖子的記錄。

... 

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

...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM