Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to best handle per-Model database connections with ActiveRecord?

I'd like the canonical way to do this. My Google searches have come up short. I have one ActiveRecord model that should map to a different database than the rest of the application. I would like to store the new configurations in the database.yml file as well.

I understand that establish_connection should be called, but it's not clear where. Here's what I got so far, and it doesn't work:

class Foo < ActiveRecord::Base
    establish_connection(('foo_' + ENV['RAILS_ENV']).intern)
end
like image 563
Terry G Lorber Avatar asked Sep 26 '08 18:09

Terry G Lorber


2 Answers

Also, it is a good idea to subclass your model that uses different database, such as:

class AnotherBase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "anotherbase_#{RAILS_ENV}"
end

And in your model

class Foo < AnotherBase
end

It is useful when you need to add subsequent models that access the same, another database.

like image 150
Priit Avatar answered Sep 17 '22 12:09

Priit


Heh. I was right! More cleanly:

class Foo < ActiveRecord::Base
    establish_connection "foo_#{ENV['RAILS_ENV']}"
end

Great post at pragedave.pragprog.com.

like image 43
Terry G Lorber Avatar answered Sep 18 '22 12:09

Terry G Lorber