ActiveRecord Extension With Different Tables

Hi,

Is it possible in rails to write a generic ActiveRecord::Base child class which is bound with a table of our choice on runtime? for example if it has two functions ‘foo’ and ‘bar’ then i should be able to provide a table name on runtime e.g. ‘table-a’ or ‘table-b’ and execute these functions on it?

Regards,

Usman

Probably doable (hackable) but I think it’d be extremely unidiomatic Rails. If you could tell us what you’re trying to achieve we might be able to suggest a better solution.

Cheers
Greg

I cannot find an alternative to this. What i’m trying to do is write a generic interface which can answer generic queries like search based on specific column and aggregate queries etc. Underlying table is provided to the Model on initialization and I want it hooked with that table so that I can run these active record generic queries (and some generic extensions) on the underlying table.

Also, how do I hack it? Is there any downside of doing it?

Regards

If you want methods available in a number of models you can derive an
intermediary class from ActiveRecord base, provide the methods in there,
and derive your models from the intermediary.

Colin

What Colin said. Alternatively, you could write a concern and include it in
models you want to support in the search feature.

Actually these tables and models are dynamically added to the database, every addition requires creating a new model in the system which contains nothing but the table name. I’m trying to avoid that by creating a single model which can handle multiple tables given a table name using ActiveRecord query interface.

Hi,