Joh*_*ohn 3 sqlite ruby-on-rails rails-activerecord
我正在为我的网站开发作品集,因此我决定为每个作品集增加技能。
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
Run Code Online (Sandbox Code Playgroud)
当我在索引页面上单击销毁时,
SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "portfolios" WHERE "portfolios"."id" = ?
Run Code Online (Sandbox Code Playgroud)
错误。所有关联看起来都正确。我在其他模型上的标签也使用了相同的模式,但没有任何问题。任何帮助都会很棒。
您正在从投资组合表中删除,但是表Portfolio_skills有一列将其引用为外键。因此,错误。
尝试删除父项而不检查并删除其关联的子项会导致数据不一致。可以使用此异常来防止这种情况。
依赖于Rails的destroy将在删除父级时删除关联的子级行。
尝试使用从属破坏:-
class Portfolio < ApplicationRecord
has_many :portfolio_skills, :dependent => :destroy
...
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2915 次 |
| 最近记录: |