簡體   English   中英

Rails InvalidForeignKey

[英]Rails InvalidForeignKey

我正在為我的網站開發一個投資組合,我決定為每個投資組合項目添加技能。

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" = ?

錯誤。 所有的協會都是正確的。 我在其他模型上對我的標簽使用了相同的模式,它沒有任何問題。 任何幫助都會很棒。

您正在從投資組合表中刪除,但表portfolio_skills有一列將其作為外鍵引用。 因此錯誤。

嘗試刪除父項而不檢查和刪除其關聯的子項可能會導致數據不一致。 這個例外是為了防止這種情況。

Rails依賴destroy將在刪除父項時處理刪除關聯的子行。

嘗試使用依賴的破壞: -

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

暫無
暫無

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

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