gpt4 book ai didi

ruby-on-rails - 如何动态设置模型的表名?

转载 作者:太空宇宙 更新时间:2023-11-03 18:10:26 25 4
gpt4 key购买 nike

我有一个遗留数据库 (oracle),在那个数据库中我有几个包含不同数据但结构相同的表。我不允许以任何方式更改数据库架构!

我想要一个 DRY ActiveRecord 模型从正确的表中获取正确的数据。问题是我需要动态覆盖 self.table_name 才能正常工作。

这是我的代码:

ActiveRecord:Base Class 将被所有类似的表继承

class ListenLoc < ActiveRecord::Base
@@table_name = nil

def self.table_name
@@table_name
end

default_scope { where(validated: 1).where("URL_OK >= 0") }
scope :random_order, -> { order('DBMS_RANDOM.VALUE') }
scope :unvalidated, -> { unscope(:where).where(validated: 0) }


def self.get_category(cat_id)
where("cat_id = ?", cat_id)
end

def self.rand_sample(cat_id, lim)
where("cat_id = ?", cat_id).random_order.limit(lim)
end
end

子类看起来是这样的:

一个

class ListenLocA < ListenLoc
@@table_name = 'LISTEN_ADDR_A'
self.sequence_name = :autogenerated
belongs_to :category, class_name: 'ListenLocCatA', foreign_key: 'cat_id'
belongs_to :country, class_name: 'Country', foreign_key: 'country_id'
end

B.

class ListenLocB < ListenLoc
@@table_name = 'LISTEN_ADDR_B'
self.sequence_name = :autogenerated
belongs_to :category, class_name: 'ListenLocCatB', foreign_key: 'cat_id'
belongs_to :country, class_name: 'Country', foreign_key: 'country_id'
end

上面的方法有效,但是我已经注意到在进行特定的选择查找时存在一些陷阱。

这是一个好方法吗?有没有更好的方法来动态传递 self.table_name

更新:

有人会认为这应该可行,但我得到一个错误,指出该表不存在,因为 ActiveRecord 尝试在创建对象之前验证该表,并且 self.table_name 未在 ListenLoc 模型上动态设置。

class ListenLocB < ListenLoc
self.table_name = 'LISTEN_ADDR_B'
self.sequence_name = :autogenerated
belongs_to :category, class_name: 'ListenLocCatB', foreign_key: 'cat_id'
belongs_to :country, class_name: 'Country', foreign_key: 'country_id'
end

最佳答案

我意识到,我可以只使用 superclass 而无需使用我最终使用的全局变量。这不会像全局变量那样造成竞争条件问题。

class ListenLocB < ListenLoc
superclass.table_name = 'LISTEN_ADDR_B' # or ListenLoc.table_name
self.sequence_name = :autogenerated
belongs_to :category, class_name: 'ListenLocCatB', foreign_key: 'cat_id'
belongs_to :country, class_name: 'Country', foreign_key: 'country_id'
end

关于ruby-on-rails - 如何动态设置模型的表名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35085057/

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