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.
D2ff155cd04fa175620d2f3495b11b08?d=identicon&s=25 Lorenzo (Guest)
on 2006-05-17 01: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
D2ff155cd04fa175620d2f3495b11b08?d=identicon&s=25 Guest (Guest)
on 2006-05-17 10: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
5e518814b76962fdd1ad0e74dfac5ea7?d=identicon&s=25 Martin Gamsjaeger (Guest)
on 2006-05-17 19: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.