Rails 模型名称间距相关销毁导致 mysql 错误未知字段



我在一个名为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

为什么活动记录使用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

我真的不喜欢它,但现在必须这样做。

相关内容

  • 没有找到相关文章

最新更新