Forum: Ruby on Rails Dynamically choosing schema using one Model

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.
Lorenzo (Guest)
on 2006-05-17 03:35
Hi all,

is there a way in RoR to dynamically set the table to which the Model
must refer to? I'd like to create a sorta "dispatcher" that chooses the
table for the Model based on an HTTP/GET var. To put it in another way
my Model would be fed with data coming from different tables based on
this var passed from the querystring.

Thanks,
Lorenzo
Guest (Guest)
on 2006-05-17 12:46
Lorenzo wrote:
> is there a way in RoR to dynamically set the table to which the Model
> must refer to? I'd like to create a sorta "dispatcher" that chooses the
> table for the Model based on an HTTP/GET var. To put it in another way
> my Model would be fed with data coming from different tables based on
> this var passed from the querystring.

Hi,

a small correction to my previous post: I actually need to dynamically
choose the _database_ to which attach to. My scenario is, infact, having
N databases with the same tables structure. Was it only a table problem
I could have used, I guess, the set_table_name method.

Thanks again,
Lorenzo
Martin G. (Guest)
on 2006-05-17 21:22
(Received via mailing list)
Hi Lorenzo,

You can reference sections like

foo_development:
  adapter: mysql
  database: foo
  username: foo
  password: ###
  host: localhost

foo_test:
  adapter: mysql
  database: foo
  username: foo
  password: ###
  host: localhost

foo_production:
  adapter: mysql
  database: foo
  username: foo
  password: ###
  host: localhost

from your database.yml like so:

class Foo< ActiveRecord::Base
	establish_connection "foo_#{RAILS_ENV}"
end

You can create different sections for your different dbs in your
database.yml and reference them using establish_connection. Then you
can implement your dispatcher the way you like. Does this help?

cheers
Martin
This topic is locked and can not be replied to.