Rails模型命名空间依赖销毁导致mysql错误未知字段

时间:2015-03-20 16:46:09

标签: ruby-on-rails-4 activerecord namespaces dependent-destroy

我在一个名为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_fieldsinstance_id而不是jira_generic_fieldsjira_instance_id以及如何在保持模型位于相同JIRA命名空间的同时解决此问题?

1 个答案:

答案 0 :(得分:0)

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

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