Rails使用多个数据库 - 没有将nil隐式转换为String

问题描述 投票:0回答:2

我正在尝试建立与另一个数据库的连接

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

知道为什么吗?

ruby-on-rails rails-activerecord octopus
2个回答
1
投票

你的问题是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.

1
投票

值得一提的是为什么我没有正确使用代码。我们也使用Octopus gem(用于运行多个数据库的gem)。当Octopus打开时,原生的establish_connection方法似乎不起作用:(。

对于你们所有人 - 使用octopus_establish_connection但要注意:https://github.com/thiagopradi/octopus/issues/101

© www.soinside.com 2019 - 2024. All rights reserved.