We have a Rails 3 application with a PostgreSQL database (with ~10 tables) mapped by activerecord
. Everything's working fine.
However, we could also like to use:
mongoid
gem).neo4j-rails
gem) instead of PostgreSQL for some tables.Using a database with one Rails ORM is simple, thanks to database.yml
. But when there's more than one ORM, how can we process? Is there a good way to do so? For instance, ActiveHash (and ActiveYaml) can work well with ActiveRecord. I think there could be a possibility to let differents ORM working together. Thanks for any tips.
In Ruby on Rails, ORM is: Database Independent - There is no need to write code in a particular database. Simply start a project using MySQL and change it to SQLite later on. Reduces Code - ORM provides the concept of abstraction, which means there's no need to repeat the same code again and again.
In the past, to build a web application you required the skills to code in your business logic. Rails is a Model-View-Controller web framework that uses an ORM in the form of ActiveRecord for the Model layer.
Object Relational Mapping is a way to manage database data by "mapping" database tables to classes and instances of classes to rows in those tables. Active Record is just one of such ORMs, others include: Sequel.
Rails 6.0 ships with all the rails tasks you need to use multiple databases in Rails. Running a command like bin/rails db:create will create both the primary and animals databases.
This really depends on the type of ORM. A great way to do this is by using inheritance. For example you can have multiple databases and adapters defined in your database.yml file. You can easily talk to these using the ActiveRecord establish_connection method.
# A typical Active record class
class Account < ActiveRecord::Base
...
end
# A new database connection
class NewConnection < ActiveRecord::Base
self.abstract_class = true
establish_connection "users_database"
end
# A new Active record class using the new connection
class User < NewConnection
...
end
The only down side here is that when you are connection to multiple active record databases migrations can get a little bit dicey.
Mixing ORM's
Mixing ORMS is easy. for example mongodb (with mongoid), simply dont inherit from active record and include the following in the model you want to use mongo:
class Vehicle
include Mongoid::Document
field :type
field :name
has_many :drivers
belongs_to :account
end
ORMs built on top of active model play very nicely together. For example with mongoid you should be able to define relations to ActiveRecord models, this means you can not only have multiple databases but they can easy communicate via active model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With