2014-07-20 17 views
1

拥有一个包含多个表的数据库。所有表具有相同的结构。我正在编写一个小型的Web应用程序来处理Ruby/Sinatra上的这个数据库。我想简化使用ORM的工作表 - Active Record或DataMapper(首选)。对于使用多个表的单一模式的手册提供的是这样的:ORM一个模型 - 乘法表

class Table 
    include DataMapper::Resource 
    property id, Serial 
    property item, String 
end 

class TableA < Table 
    self.table_name = 'table_a' 
end 

class TableB < Table 
    self.table_name = 'table_b' 
end 

这可怎么好十几张桌子来完成,而不copypaste?

如果可能,决定应该是添加/删除表而不更改代码/设置并重新启动应用程序的可能性。

喜欢的东西:

# Model declaration 

DataMapper.finalize 

itemA = Table.new (use_table: 'table_a') 
itemB = Table.new (use_table: 'table_b') 
+0

http://stackoverflow.com/questions/5981724/multiple-database-tables-within-one-ar-model-in-rails-3 – Reisenfag

回答

0

一来实现这一目标是使用eval的方式。

class Table 
    include DataMapper::Resource 
    property id, Serial 
    property item, String 
end 

table_names = {'TableA' => 'table_a', 'TableB' => 'table_b'} 

table_names.each do |klass_name, table_name| 
eval <<DYNAMIC 
    class #{klass_name} < Table 
    self.table_name = '#{table_name}' 
    end 
DYNAMIC 
end 
+0

作为一个解决方案是可能的,但并不需要很什么。补充了这个问题。 – Reisenfag

+0

它看起来像你想使用工厂模式。你可以在'Table'中添加一个方法来接受'table_name'并返回'Table'的子类。您可以通过在名称索引的“Table”中添加一个所有子类的缓存来实现此方法。如果在查找中没有找到当前名称,则生成一个新的子类并将其添加到索引中。 – Nishu

+0

我在Active Record中找到解决方案。这是代码只是工作: '类测试<的ActiveRecord :: Base' 'end' 'Test.table_name = “tests_a”'' 意达= Test.new' 'itema.item = “AAA”' 'itema.save' 'Test.table_name = “tests_b”'' = itemb Test.new' 'itemb.item = “BBB”'' itemb.save' – Reisenfag