views:

252

answers:

3

How would I go about creating multiple database tables at runtime that utilize the same model given that rails wants to infer the table name from the model name? I want to be able to create a new object based on a model, then create a new table with a unique name that the object will reference. Does anyone have any examples or advice they can share to help me find a solution?

+4  A: 

This sounds like an architectural problem - why would you have clones of the same model instead of storing them all in the same table?

In the relational database model, a relation is what defines a row or tuple, meaning it is the set of attributes about the key. Any other similar sets of attributes belong in the same relation (table).

Cade Roux
A: 

Creating the table is possible, I guess. Something like "CREATE TABLE newtab AS SELECT * FROM oldtab WHERE 0=1" executed using ActiveRecord::Base.connection.execute.

You may then somehow be able to execute set_table_name to point your model to the created table.

It would really help to get more information on what problem you perceive yourself to have that would require this kind of twisted solution. The reason it's hard to do in Rails is that you really shouldn't need to do it. I would hope that there's a simpler alternative architecture.

Mike Woodhouse
A: 

Unsure why on earth you'd want to do this, but it is possible:

runtime_table_name = "random"

ActiveRecord::Migration.create_table(runtime_table_name) do
  # Table definition goes here
end

eval <<-EOS
  class #{runtime_table_name.classify} < YourBaseModel
    set_table_name #{runtime_table_name.inspect}
  end
EOS

runtime_model = runtime_table_name.classify.constantize
runtime_model.find(:all)

You just need to replace YourBaseModel with whichever model you'd like your runtime models to be like.

Nathan de Vries
The reason I'm doing this is the actual thing I'm modeling isn't static. I am displaying a filesystem tree that a user can interact with. I traverse the filesystem and build the table as the user requests it as the physical structure may have changed since the last time I did so.