我正在尝试建立与另一个数据库的连接
class Something < ApplicationRecord
self.abstract_class = true
establish_connection {adapter:"postgresql",host:"localhost",port:5432,database:"dev_x",user:"user",password:"1234"}
end
但每当我尝试运行一个方法(例如:Something.all)时,我收到错误:
no implicit conversion of nil into String
知道为什么吗?
你的问题是Something
是一个抽象类:
class Something < ApplicationRecord
self.abstract_class = true # <-------------------------
抽象类并不意味着直接实例化,您应该将它们子类化并实例化子类。 abstract_class
属性或多或少是一种在不调用STI(单表继承)的情况下子类化模型的方法。
要么使用Something
作为第二个数据库中模型的基类,要么删除self.abstract_class = true
以使其成为“真正的”模型类。
至于你的no implicit conversion of nil into String
错误来自哪里,请记住抽象模型类没有表名,也无法实例化,来自the documentation:
class Shape < ActiveRecord::Base
self.abstract_class = true
end
Polygon = Class.new(Shape)
Square = Class.new(Polygon)
Shape.table_name # => nil
Polygon.table_name # => "polygons"
Square.table_name # => "polygons"
Shape.create! # => NotImplementedError: Shape is an abstract class and cannot be instantiated.
值得一提的是为什么我没有正确使用代码。我们也使用Octopus gem(用于运行多个数据库的gem)。当Octopus打开时,原生的establish_connection
方法似乎不起作用:(。
对于你们所有人 - 使用octopus_establish_connection
但要注意:https://github.com/thiagopradi/octopus/issues/101