TalentBox / sequel-rails

A gem for using Sequel with Rails 5.x, 6.x, 7.x, 8.x
http://talentbox.github.io/sequel-rails/
MIT License
326 stars 81 forks source link

Question: multiple databases? #74

Open jihwans opened 10 years ago

jihwans commented 10 years ago

I could not figure this out and could not google to find any useful info.

How do you handle multiple databases with sequel-rails?

With activerecord they say it can be done by defining a super class of model with this line:

establishconnection "att#{Rails.env}"

JonathanTron commented 10 years ago

There's no support in sequel-rails for multiple database.

You can replicate what's possible with ActiveRecord (note I've never done it myself) using the Sequel::Plugins::Sharding

jihwans commented 10 years ago

I've been digging the source code of Sequel::Model and found a way. I do not like to 100% but.. it works.

First put a module file in models folder something like this: odb.rb:

module Odb
  def self.Model(source)
    c = Sequel::Model(
        Sequel.connect(Rails.configuration.database_configuration["odb_#{Rails.env}"]
        # assuming database.yml has odb_* entries
      )
    c.set_dataset(source)
    # ot, to add table prefix:
    #c.set_dataset(('prefix_' + source.to_s).to_sym)
  end
end

in models/odb folder, my_model.rb:

class Odb::MyModel < Odb::Model(:my_models)
end

Actually, there is another way, which is a bit better, where a class is defined in the module, instead of defining model class emitter function.

Either way, what I do not like about them is that I have to make connection first. Many times, I find it beneficial to delay the connection until the moment the model was invoked with some action that requires connection...

JonathanTron commented 10 years ago

Yes, but that's how Sequel::Model works, they require to have access to the underlying table schema on load.