Forum: Ruby on Rails Dynamic table names.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F148ec0cad8ea241b1cfd80e7ec8a7df?d=identicon&s=25 Fredrik (Guest)
on 2007-02-06 17:20
(Received via mailing list)
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
F148ec0cad8ea241b1cfd80e7ec8a7df?d=identicon&s=25 Fredrik (Guest)
on 2007-02-06 17:40
(Received via mailing list)
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
F148ec0cad8ea241b1cfd80e7ec8a7df?d=identicon&s=25 Fredrik (Guest)
on 2007-02-06 17:44
(Received via mailing list)
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
This topic is locked and can not be replied to.