gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:03:04 27 4
gpt4 key购买 nike

我在名为 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命名空间?

最佳答案

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

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

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

关于ruby-on-rails-4 - Rails 模型命名空间依赖销毁导致 mysql 错误未知字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29171730/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com