我正在尝试将Rails用于数据库,其中架构不受我的控制。
关于此数据库的一点是,单独的进程以下列方式为特定客户端生成表名:
prefix_clientname1
prefix_clientname2
prefix_clientname3
所有这些表都具有相同的架构,但具有不同的数据。
创建模型以访问此数据的最佳方法是什么?
如果我不能直接通过课程访问它们,我不一定感到困扰:使用ModelName.client("foo").find(:all)
或类似的API可能会有用。
甚至可以使用ActiveRecord,还是应该查看DataMapper?
答案 0 :(得分:2)
我想出的解决方案是定义一个通过元编程定义类的类。
class Orders
def self.by_name(identifier)
class_name = "Orders" + identifier.classify
if Object.const_defined?(class_name)
return Object.const_get(class_name)
else
new_class = Class.new(ActiveRecord::Base) do
set_table_name 'orders_' + identifier
end
Object.const_set(class_name, new_class)
return new_class
end
end
end
这可以通过调用Orders.by_name
来访问表格:
Orders.by_name("foobar").find(:all, :limit => 5)
OrdersFoobar.find(:all, :limit => 5)
显然,它们可以在启动时初始化。