我的应用程序中有几个表共享大多数列。我在一个模型中编写了所有验证,并试图使所有其他模型都继承自该模型,但出现了 ActiveRecord::SublassNotFound
错误。
这是我的模型的代码:
医院.rb
class Hospital < ActiveRecord::Base
validates :cnes, presence: true, numericality: true
validates :name, presence: true, length: { maximum: 80 }
validates :address, presence: true, length: { maximum: 50 }
validates :neighborhood, presence: true, length: { maximum: 30 }
validates :phone, presence: true, length: { in: 10..25 }
validates :latitude, :longitude, presence: true, length: { maximum: 20 }
validates :type, presence: true
药房.rb
class Pharmacy < Hospital
self.table_name = 'pharmacies'
end
这两个表具有完全相同的列,我选择使用 MTI 来为我的数据库提供更大的可扩展性,因为药房和医院也将具有多个模型的 STI。
这是我遇到的错误:
ActiveRecord::SubclassNotFound:
Invalid single-table inheritance type: Hospital is not a subclass of Pharmacy
我想重用我打算为这两个模型实现的验证和一些方法。
最佳答案
你需要的是一个抽象类:
class Hospital < ActiveRecord::Base
self.abstract_class = true
# validations...
end
然后从您的子类中删除表名。
关于ruby-on-rails - 在 Rails 中实现多表继承的最干的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56215038/