所以我安装了gem acts_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”=?
我相信这个问题是你需要在删除帖子时销毁依赖帖子的记录。
...
has_many :hashtaggings, dependent: :destroy
has_many :hashtags, through: :hashtaggings, dependent: :destroy
...