How to Best Handle Per-Model Database Connections with Activerecord

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

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.

more than one database per model

Try taking a look as this question over here.
How to best handle per-Model database connections with ActiveRecord?

They define the databases in the database.yml file like normal and call this in the model:

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

Used info from Priit's answer

How best to associate an Address to multiple models in rails?

One way would be standard Rails polymorphism:

class Address
belongs_to :addressable, :polymorphic => true
end

class UserProfile
has_one address, :as => :addressable
end

class Event
has_one address, :as => :addressable
end

It could be the nagging feeling you have about this is that you can't create a db-level constraint with Rails-style polymorphic relationships. The alternative (suggested by Dan Chak in Enterprise Rails) is like your #1 option, where you do indeed create a separate id field for each type of relationship. This does leave unused fields, but it also allows for constraints. I can see the argument for both, but the Rails community has been using AR polymorphism for some time with apparently good success. I use it without hesitation. But if that bugs you, you can use Chak's approach. It's a lot more work. : )

EDIT: @Slick86, migration would look something like:

class CreateAddresses < ActiveRecord::Migration
def change
create_table :addresses do |t|
t.integer :addressable_id
t.string :addressable_type
end
end
end

Best way to validate an external gem's ActiveRecord model

Ruby has so-called "open classes". You can open any class (at any time) and add more methods to it. This should work:

module Library
class Model
validates :me_too, presence: true
end
end

It opens already defined Library::Model and just adds one more line of code to what's already there (not replacing/removing that existing code).

Note that this depends on Library::Model being already loaded (this is not guaranteed). This should be a safer alternative:

Library::Model.instance_eval do
validates :me_too, presence: true
end

It will trigger loading of Library::Model if it's not already loaded.



Related Topics



Leave a reply



Submit