0

我在一个名为 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命名空间下的同时解决此问题?

4

1 回答 1

1

最后在模型中指定 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

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

于 2015-03-24T15:22:05.970 回答