Dynamic table names

In my current project we’re using three databases and using joins
inbetween them and when working on testing, it just did not seem to
work to have multiple databases and using the set_table_name function
since it hardcodes it to one database.

From just looking around at some code, I copied and pasted this
together, which I will use to extend my models from (There are three
of them).

I could still use the one core database through the database.yml and
only extend 2 of them.

Here is what I have. Example of one of the three.

In environment.rb I have
PRODUCTS_DATABASE = “products”

lib/products_database.rb

module ARExtension
def self.included(base) #:nodoc:
base.extend(ClassMethods)
end

module ClassMethods
def ai_table_name(value)
base_table_name = PRODUCTS_DATABASE + “.” + value
if RAILS_ENV == “production”
set_table_name(base_table_name)
else
set_table_name(base_table_name + “_” + RAILS_ENV)
end
end
end
end

class ProductsDatabase < ActiveRecord::Base
include ARExtension
end

modules/testing.rb

class Testing < ProductsDatabase
ai_table_name “testings”
belongs_to :create_user, :foreign_key => “created_by”, :class_name
=> “User”
belongs_to :update_user, :foreign_key => “updated_by”, :class_name
=> “User”
end

This will produce products.testings["","_test","_development] for the
different RAILS_ENV

I was just wondering if there is a better solution out there, perhaps
something within rails to do what I need it to do.

Thanks,
Fredrik

Ok, I must have been a little confused this morning, That code would
have to be modified to support.

products["","_test","_development].testings
instead of
products.testings["","_test","_development]

Thanks,
Fredrik

This should do it.

module ARExtension
def self.included(base) #:nodoc:
base.extend(ClassMethods)
end

module ClassMethods
def ai_table_name(value)
if RAILS_ENV == “production”
set_table_name(PRODUCTS_DATABASE + “.” + value)
else
set_table_name(PRODUCTS_DATABASE + “_” + RAILS_ENV + “.” +
value )
end
end
end
end

class ProductsDatabase < ActiveRecord::Base
include ARExtension
end

Thanks,
Fredrik