【问题标题】:Using STI fails to migrate database使用 STI 迁移数据库失败
【发布时间】:2018-08-07 02:59:14
【问题描述】:

一段时间以来一直在研究这个特定问题,并认为是时候寻求帮助了。我看过以下链接,但没有运气

PG undefinedtable error relation users does not exist

https://github.com/rails/rails/issues/3279

我的问题与https://github.com/rails/rails/issues/6470 有点相似,但不完全一样。

我有一个名为 type_tables 的类,它是 STI 的基类,这里是 STI 的架构

create_table "type_tables", force: :cascade do |t|
 t.string "title"
 t.string "desc"
 t.string "type"
 t.string "uom"
 t.index ["title"], name: "index_type_tables_on_title"
 t.index ["type"], name: "index_type_tables_on_type"
end

现在,这个类型表只是我项目中的一个基类,其他类型如 device_type、certificate_type 等都继承自它。

type_table 的模型

class TypeTable < ApplicationRecord
  validates :title, presence: true, uniqueness: true
end

另一个 device_type 模型

class DeviceType < TypeTable
  has_many :certificates
  #this is where the error originates
  GARMIN_ID = find_by(title: "Garmin").id

  #when i use some constant value rails successfully executes the 
   db:create task in my rake file
  GARMIN_ID = 22

end

现在,有趣的是,它只在第一次显示这种行为,即当我的 Postgres 数据库中没有现有表时。当我成功创建和迁移我的应用程序架构并且表存在时,此行将每次都有效。

GARMIN_ID = find_by(title: "Garmin").id

我的想法是,由于它试图在 type_tables 关系中查找列并且该关系不存在,因此会引发不存在关系错误。虽然你在控制台看到的错误是

2018-08-07 02:24:49.281 UTC [69] FATAL:  database "myappdb" does not 
exist

mlcot_api | /usr/local/bundle/gems/activerecord-5.1.3/lib/active_record/connection_adapters/postgresql_adapter.rb:699:in 
`rescue in connect': FATAL:  database "myappdb" does not exist 
(ActiveRecord::NoDatabaseError)

当我使用手动创建数据库时

docker-compose run api rake db:create

然后运行 ​​docker-compose up 我得到

ERROR:  relation "type_tables" does not exist at character 566

/usr/local/bundle/gems/activerecord- `async_exec': PG::UndefinedTable: 
ERROR:  relation "type_tables" does not exist 
           (ActiveRecord::StatementInvalid)
           WHERE a.attrelid = '"type_tables"'::regclass

注意:我知道解决方法并且我的应用程序可以运行,但我依赖于具有所有注释代码的特定分支 第一次构建我想要删除的数据库时需要。

任何帮助表示赞赏并提前致谢。

【问题讨论】:

  • docker-compose run api rake db:migratedocker-compose run api rake db:create 之后怎么样?
  • 中止迁移 ` rake 中止! ActiveRecord::StatementInvalid: PG::UndefinedTable: 错误: 关系 "type_tables" 不存在第 8 行: WHERE a.attrelid = '"type_tables"'::regclass `

标签: ruby-on-rails activerecord docker-compose rails-activerecord sti


【解决方案1】:

在加载模型定义时访问数据库是一个非常糟糕的主意。不要那样做。

相反,请考虑使用仅在第一次需要时检索值的类方法:

def self.garmin_id
  @garmin_id ||= find_by(title: "Garmin").id
end

就我个人而言,我强烈反对这种持久性——最好花一个查询为每个需要它的请求重新检索它——但这更多是设计判断的问题。

【讨论】:

  • 感谢您的帮助,但我试图了解为什么会首先出现错误?
  • 因为您正在访问模型定义中的数据库,并且应用程序希望在执行创建表的数据库工作之前启动(包括加载模型定义)。这是一个先有鸡还是先有蛋的问题。
  • 没错,这就是为什么我真的很困扰,因为我是 Rails 新手。还是谢谢。
猜你喜欢
  • 2018-04-06
  • 1970-01-01
  • 2014-08-02
  • 1970-01-01
  • 2014-08-12
  • 2016-12-19
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多