Rails 3 / ActiveRecord: how to dynamically change table name during query?

I want to change the table name of the ActiveRecord model class during the query dynamically.


For example, there are many tables that have a similar structure (columns):

mydb: sample_data_12222 sample_data_12223 sample_data_12224 sample_data_12225 ... 

So I want to do this ...

_1. The definition of the base class of the model as follows:

 class SampleData < ActiveRecord::Base 

_2. Changing the target table during a query, for example:

 def action_method SampleData.set_table_name "sample_data_#{params[:id]}" @rows = SampleData.all 

It seems that the above code is right if it runs on a non-streaming environment (e.g. Passenger / mod_rails). But it is not thread safe , so it may not work in a streaming environment (for example, on JRuby-Rack).

I also tried to create a delived class as follows:

 def action_method @model_class = Class.new(SampleData) @model_class.set_table_name "sample_data_#{params[:id]}" @rows = @model_class.all 

But this causes a memory leak, although the extended model class is no longer used after the request is complete. :(


Is there a better way to do this?

+6
source share
1 answer

I would use class variables:

 class SampleData < ActiveRecord::Base class << self @@model_class = {} # Create derived class for id @@model_class[id] = Class.new(SampleData) @@model_class[id].set_table_name "sample_data_#{id}" # Repeat for other IDs end end 

Now you can use derived classes over and over again without causing memory leaks.

Depending on your actual situation (for example, you do not know the identifiers in advance), you can check if the identifier is already present in Hash dynamically and add it if not.

+6
source

Source: https://habr.com/ru/post/896872/


All Articles