foreign key constraint, blog post, acts_as_votable

138 Views Asked by At

So I installed the gem acts_as_votable or whatever it's called. Great little voting system. However in my admin when I go to delete the blog post, I get a foreign key constraint failed error message with the sqlite. I know it has to do with db tables where if you try to delete a record on one table that has a foreign key on another table, that causes an issue unless on_delete: :cascade is defined for the foreign key, etc. I'm not sure how I can do this for the acts_as_votable gem. Anyone know? Thanks!

blog model:

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

blog controller:

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

The page view:

<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 %>

Error message:

SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "home_blogs" WHERE "home_blogs"."id" = ?

1

There are 1 best solutions below

3
Rockwell Rice On

I believe this issue is you need to destroy the records that rely on the post when deleting the post.

... 

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

...