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?
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).
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.
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.