Rails无效的外键约束错误

4

我正在为我的网站开发一个作品集,我决定在每个作品展示中添加技能标签。

class PortfolioSkill < ApplicationRecord
  belongs_to :portfolio
  belongs_to :skill
end

class Portfolio < ApplicationRecord

  has_many :portfolio_skills
  has_many :skills, through: :portfolio_skills


  def all_tags=(names)
    self.skills = names.split(",").map do |name|
      Skill.where(name: name.strip).first_or_create!
  end
end

 def all_tags
  self.skills.map(&:name).join(", ")
 end

 def remove_skill_tags
    PortfolioSkill.where(portfolio_id: id).destroy_all
 end


end



 create_table "portfolio_skills", force: :cascade do |t|
     t.integer "portfolio_id"
     t.integer "skill_id"
     t.datetime "created_at", null: false
     t.datetime "updated_at", null: false
     t.index ["portfolio_id"], name:     "index_portfolio_skills_on_portfolio_id"
     t.index ["skill_id"], name: "index_portfolio_skills_on_skill_id"
  end

create_table "portfolios", force: :cascade do |t|
    t.string "name"
    t.string "client"
    t.date "completed"
    t.text "about"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "long_landscape"
    t.string "cover"
    t.integer "category_id"
    t.index ["category_id"], name: "index_portfolios_on_category_id"
  end

当我在主页点击“destroy”时,我会得到以下信息:
SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "portfolios" WHERE "portfolios"."id" = ?

出现错误。所有关联看起来都是正确的。我在其他模型上使用了相同的模式来标记标签,并且没有任何问题。希望能得到帮助。

1个回答

12

您正在从投资组合表中删除内容,但投资组合技能表具有引用它作为外键的列。因此会出现错误。

尝试删除父项而不检查和删除其关联子项可能导致数据不一致。该异常已经存在以防止这种情况发生。

Rails dependent destroy功能将在删除父项时同时删除关联的子行。

尝试使用dependent destroy:

class Portfolio < ApplicationRecord
  has_many :portfolio_skills, :dependent => :destroy
  ...
end

你能否详细解释一下?它的确起作用了,但我还是不明白为什么。 - John
发生的情况是当您删除一个投资组合时,投资组合_skills表中仍然存在与该投资组合相关联的关联。使用:dependent => destroy,您还将删除这些依赖项。您的意思是,“当我删除一个投资组合时,也删除与之相关的portfolio_skills。” - hashrocket

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接