Rails 模型命名空间相关的破坏导致 mysql 错误未知字段

Rails model namespacing dependent destroy causes mysql error unknown field

我在名为 jira 的单独文件夹中有几个模型(instance.rb、generic_field.rb 等)。它们都在 JIRA 下命名空间,例如 JIRA::Instance < ActiveRecord::Base、JIRA::GenericField < ActiveRecord::Base。这是两个模型:

class JIRA::GenericField < ActiveRecord::Base
  self.table_name = "jira_generic_fields"
  belongs_to :jira_instance, class_name: JIRA::Instance
end


class JIRA::Instance < ActiveRecord::Base
  self.table_name = "jira_instances"
  has_many :jira_generic_fields, dependent: :destroy, class_name: JIRA::GenericField
end

表的数据库架构:

create_table "jira_generic_fields", force: true do |t|
  t.string  "jira_id"
  t.string  "name"
  t.integer "jira_instance_id",      null: false
end

create_table "jira_instances", force: true do |t|
  t.string "jira_link"
  t.string "crowd_link"
end

在我的 rails 控制台中,我创建了一个 JIRA::Instance 对象,当我试图销毁它时,我得到了这个:

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'jira_generic_fields.instance_id' in 'where clause': SELECT `jira_generic_fields`.* FROM `jira_generic_fields`  WHERE `jira_generic_fields`.`instance_id` = 1

为什么 ActiveRecord 使用 jira_generic_fields.instance_id 而不是 jira_generic_fields.jira_instance_id 以及如何在保持模型相同的情况下解决此问题 JIRA 命名空间?

最后在模型中指定 foreign_key 解决了这个问题...

class JIRA::GenericField < ActiveRecord::Base
  self.table_name = "jira_generic_fields"
  belongs_to :jira_instance, foreign_key: 'jira_instance_id', class_name: JIRA::Instance
end

class JIRA::Instance < ActiveRecord::Base
  self.table_name = "jira_instances"
  has_many :jira_generic_fields, dependent: :destroy, foreign_key: 'jira_instance_id', class_name: JIRA::GenericField
end

我不是很喜欢,但现在必须这样做。