Rails应用DELETE请求返回500错误 误查HABTM关联中间表问题
问题原因
Rails 中 has_and_belongs_to_many(HABTM)关联默认遵循按关联模型名称字母顺序拼接复数形式的中间表命名规则:Developer 首字母D排序在 Team 首字母T之前,所以默认查找的中间表名为 developers_teams,但你的迁移文件实际创建的中间表名为 teams_developers,名称不匹配。
GET、POST请求未触发中间表操作所以可以正常运行,DELETE操作执行时ActiveRecord会自动清理该开发者对应的关联中间表记录,查找不到对应表就抛出500错误。
解决方法
两种方案二选一即可:
方案1:修正中间表名称(推荐,符合Rails默认约定)
如果迁移还可回滚,直接修改迁移文件中的表名,再重新执行迁移:
# 修改迁移文件中的表名 create_table :developers_teams, id: false do |t| t.belongs_to :team t.belongs_to :developer end
如果已经在生产环境运行过迁移无法回滚,新建迁移重命名表即可:
class RenameTeamsDevelopersJoinTable < ActiveRecord::Migration[6.1] def change rename_table :teams_developers, :developers_teams end end
方案2:手动指定中间表名称
不想修改现有表的话,直接在两个关联模型中显式指定关联的中间表名即可:
# team.rb class Team < ApplicationRecord validates :name, presence: true has_many :messages # 手动指定中间表名 has_and_belongs_to_many :developers, join_table: :teams_developers end # developer.rb class Developer < ApplicationRecord validates :full_name, presence: true # 手动指定中间表名,可补充dependent: :delete_all 自动清理关联记录 has_and_belongs_to_many :teams, join_table: :teams_developers, dependent: :delete_all end
内容的提问来源于stack exchange,提问作者Lazlo
相关产品推荐
相关产品推荐

