Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
229 changes: 229 additions & 0 deletions source/add-existing.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
.. _mongoid-add-to-existing:

======================================
Add {+odm+} to an Existing Application
======================================

.. facet::
:name: genre
:values: tutorial

.. meta::
:keywords: ruby framework, odm, migrate

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

Overview
--------

In this guide, you can learn how to add {+odm+} to an existing Sinatra
or Ruby on Rails (Rails) application. To learn how to set up a new
application that uses {+odm+}, see one of the following guides:

- :ref:`mongoid-quick-start-rails`
- :ref:`mongoid-quick-start-sinatra`

Sinatra Application
-------------------

To start using {+odm+} in an existing Sinatra application, perform
the following steps:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

S: change line to "perform the following steps:" or something similar to avoid double "follow"


1. Add the ``mongoid`` dependency to your application's ``Gemfile``.

#. Create a ``config/mongoid.yml`` configuration file and specify your
connection target, as shown in the
:ref:`mongoid-quick-start-sinatra-connect-to-mongodb` step of the
Quick Start guide.

#. Create an application file and load your configuration file, as shown
in the :ref:`mongoid-quick-start-sinatra-view-data` step of the Quick
Start guide.

#. Create {+odm+} models to interact with your data.

Rails Application
-----------------

You can add {+odm+} to an existing Rails application to run alongside
other Active Record adapters. To use a combination of adapters, you
can add the ``mongoid`` dependency and populate the configuration file
with your connection information to start using MongoDB in your
application.

To adapt an existing Rails application to use only {+odm+} instead of
Active Record, you must make other configuration changes, as
described in the following sections.

Modify Dependencies
~~~~~~~~~~~~~~~~~~~

Add the ``mongoid`` gem to your application's ``Gemfile``:

.. code-block:: ruby
:caption: Gemfile

gem 'mongoid'

To use {+odm+} as the *only* database adapter, remove or comment out any
RDBMS libraries listed in the ``Gemfile``, such as ``sqlite`` or
``pg``.

Then, install the dependencies by running the following command:

.. code-block:: sh

bundle install

{+odm+} Configuration
~~~~~~~~~~~~~~~~~~~~~

Generate the default {+odm+} configuration by running the following
command:

.. code-block:: sh

bin/rails g mongoid:config

This generator creates the ``config/mongoid.yml`` configuration file
used to configure the connection to the MongoDB deployment and the
``config/initializers/mongoid.rb`` initializer file that you can use
to set other options.

In the ``config/mongoid.yml`` file, specify your connection string and
other connection options.

Modify Frameworks
~~~~~~~~~~~~~~~~~

Open the ``config/application.rb`` file and examine the contents. If the
file uses the ``require "rails/all"`` statement to load all Rails components,
delete this statement. You must add a separate ``require`` statement
for each Rails component, as shown in the following sample
``config/application.rb`` file:

.. code-block:: ruby
:caption: config/application.rb

# Remove or comment out rails/all
#require "rails/all"

# Add the following instead of rails/all:
require "rails"

# Comment out unneeded frameworks
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

solid idea to show how to do this in code. if this is a comprehensive list, and if it isn't too burdensome to keep current, it might be good to direct them here from the opening paragraph ("...as shown in the following code example:")

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I totally understand what you mean. This list isn't necessarily what a user would need in their application to use Mongoid, it just demonstrates how to load frameworks individually.

# require "active_record/railtie" rescue LoadError
# require "active_storage/engine" rescue LoadError
require "action_controller/railtie" rescue LoadError
require "action_view/railtie" rescue LoadError
require "action_mailer/railtie" rescue LoadError
require "active_job/railtie" rescue LoadError
require "action_cable/engine" rescue LoadError
# require "action_mailbox/engine" rescue LoadError
# require "action_text/engine" rescue LoadError
require "rails/test_unit/railtie" rescue LoadError

.. note::

Because they rely on Active Record, the `ActionText
<https://guides.rubyonrails.org/action_text_overview.html>`__,
`ActiveStorage <https://edgeguides.rubyonrails.org/active_storage_overview.html>`__, and
`ActionMailbox
<https://guides.rubyonrails.org/action_mailbox_basics.html>`__
adapters cannot be used alongside {+odm+}.

Disable Active Record Adapters
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In ``config/application.rb`` and your application's other configuration
files, remove or comment out any references to
``config.active_record`` and ``config.active_storage``.

Adjust Models
~~~~~~~~~~~~~

To migrate from using Active Record to {+odm+}, you must adjust your
application's existing models.

Active Record models derive from the ``ApplicationRecord`` class and do
not have column definitions, while {+odm+} models generally have no
superclass but must include the ``Mongoid::Document`` attribute.

When creating {+odm+} models, you can define fields in the following
ways:

- Define fields explicitly
- Use :ref:`dynamic fields <mongoid-dynamic-fields>`

For example, a basic Active Record ``Post`` model might resemble the
following:

.. code-block:: ruby
:caption: app/models/post.rb

class Post < ApplicationRecord
has_many :comments, dependent: :destroy

Check failure on line 169 in source/add-existing.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.NegativeWords] Use 'remove, delete' instead of the negative word 'destroy'. Raw Output: {"message": "[MongoDB.NegativeWords] Use 'remove, delete' instead of the negative word 'destroy'.", "location": {"path": "source/add-existing.txt", "range": {"start": {"line": 169, "column": 38}}}, "severity": "ERROR"}
end

A similar {+odm+} ``Post`` model might resemble the following:

.. code-block:: ruby
:caption: app/models/post.rb

class Post
include Mongoid::Document

field :title, type: String
field :body, type: String

has_many :comments, dependent: :destroy

Check failure on line 183 in source/add-existing.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.NegativeWords] Use 'remove, delete' instead of the negative word 'destroy'. Raw Output: {"message": "[MongoDB.NegativeWords] Use 'remove, delete' instead of the negative word 'destroy'.", "location": {"path": "source/add-existing.txt", "range": {"start": {"line": 183, "column": 38}}}, "severity": "ERROR"}
end

Instead of using predefined fields, you can define the ``Post`` model by using
dynamic fields, as shown in the following code:

.. code-block:: ruby
:caption: app/models/post.rb

class Post
include Mongoid::Document
include Mongoid::Attributes::Dynamic

has_many :comments, dependent: :destroy

Check failure on line 196 in source/add-existing.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.NegativeWords] Use 'remove, delete' instead of the negative word 'destroy'. Raw Output: {"message": "[MongoDB.NegativeWords] Use 'remove, delete' instead of the negative word 'destroy'.", "location": {"path": "source/add-existing.txt", "range": {"start": {"line": 196, "column": 38}}}, "severity": "ERROR"}
end

Data Migration
~~~~~~~~~~~~~~

If you already have data in a relational database that you want to
move into MongoDB, you must perform a data migration. You don't have to

Check failure on line 203 in source/add-existing.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.ConciseTerms] 'must' is preferred over 'have to'. Raw Output: {"message": "[MongoDB.ConciseTerms] 'must' is preferred over 'have to'.", "location": {"path": "source/add-existing.txt", "range": {"start": {"line": 203, "column": 65}}}, "severity": "ERROR"}
perform schema migration because MongoDB does not require
a predefined schema to store the data.

Migration tools are often specific to datasets.
Even though {+odm+} supports a superset of Active Record associations,
model references are stored differently in collections when using
{+odm+} compared to Active Record.

Visit the following resources to learn more about migrating from an
RDBMS to MongoDB:

- `RDBMS to MongoDB Migration Guide
<https://s3.amazonaws.com/info-mongodb-com/RDBMStoMongoDBMigration.pdf>`__
in the AWS documentation

- :website:`Modernize your apps with MongoDB Atlas
</solutions/use-cases/modernize>` on the MongoDB website

Rails API
~~~~~~~~~

The process for creating a Rails API application that uses {+odm+} is
almost the same as for creating a normal application. The only

Check failure on line 226 in source/add-existing.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.Accessibility] Don't use language (such as 'normal') that defines people by their disability. Raw Output: {"message": "[MongoDB.Accessibility] Don't use language (such as 'normal') that defines people by their disability.", "location": {"path": "source/add-existing.txt", "range": {"start": {"line": 226, "column": 35}}}, "severity": "ERROR"}
difference is that you must add the ``--api`` flag when running ``rails
new`` to create the application. Migrating a Rails API application to
{+odm+} follows the same process described in the preceding sections.
9 changes: 5 additions & 4 deletions source/index.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@

/quick-start-rails
/quick-start-sinatra
/add-existing
/interact-data
installation-configuration
tutorials
schema-configuration
working-with-data
API <https://mongodb.com/docs/mongoid/master/api/>
release-notes
contributing
additional-resources
ecosystem
/release-notes
/contributing
/additional-resources

Check failure on line 26 in source/index.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.ConciseTerms] 'more' is preferred over 'additional'. Raw Output: {"message": "[MongoDB.ConciseTerms] 'more' is preferred over 'additional'.", "location": {"path": "source/index.txt", "range": {"start": {"line": 26, "column": 5}}}, "severity": "ERROR"}
/ecosystem
7 changes: 5 additions & 2 deletions source/quick-start-rails.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
.. _mongoid-quick-start-rails:

===========================
Quick Start (Ruby on Rails)
Quick Start - Ruby on Rails
===========================

.. facet::
Expand All @@ -25,6 +25,9 @@ web application, connect to a MongoDB cluster hosted on MongoDB
Atlas, and perform read and write operations on the data in your
cluster.

To learn how to integrate {+odm+} into an existing application, see the
:ref:`mongoid-add-to-existing` guide.

.. tip::

If you prefer to connect to MongoDB by using the {+ruby-driver+} without
Expand All @@ -38,7 +41,7 @@ create flexible data models.
Ruby on Rails is a web application framework for
{+language+}. Rails applications use a model-view-controller (MVC)
architecture that allows you to easily control how your data is
modeled and displayed. {+odm+} replaces the default ``ActiveRecord``
modeled and displayed. {+odm+} replaces the default Active Record
adapter for data modeling in Rails.

To learn more about Ruby on Rails, see the `Getting Started
Expand Down
5 changes: 2 additions & 3 deletions source/quick-start-rails/download-and-install.txt
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,8 @@ gems to your web application.
cd {+quickstart-rails-app-name+}

The ``--skip-active-record`` flag instructs Rails to not add
``ActiveRecord`` as a dependency. You don't need this
dependency because you will use {+odm+}
instead.
Active Record as a dependency. You don't need this
dependency because you will use {+odm+} instead.

.. tip:: MacOS Installation Issue

Expand Down
5 changes: 4 additions & 1 deletion source/quick-start-sinatra.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
.. _mongoid-quick-start-sinatra:

=====================
Quick Start (Sinatra)
Quick Start - Sinatra
=====================

.. facet::
Expand All @@ -24,6 +24,9 @@ This guide shows you how to use {+odm+} in a new Sinatra web application,
connect to a MongoDB cluster hosted on MongoDB Atlas, and perform
read and write operations on the data in your cluster.

To learn how to integrate {+odm+} into an existing application, see the
:ref:`mongoid-add-to-existing` guide.

.. tip::

If you prefer to connect to MongoDB by using the {+ruby-driver+} without
Expand Down
2 changes: 1 addition & 1 deletion source/reference/compatibility.txt
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ Mongoid is used as a drop-in replacement.
``ActionCable``, however any existing adapter (such as `Redis <https://guides.rubyonrails.org/action_cable_overview.html#redis-adapter>`_)
can be used successfully in conjunction with Mongoid models

.. [#rails-activerecord-dependency] Depends directly on ``ActiveRecord``
.. [#rails-activerecord-dependency] Depends directly on ActiveRecord

.. [#rails-activemodel-dependency] ``Mongoid::Document`` includes ``ActiveModel::Model``
and leverages ``ActiveModel::Validations`` for validations
Expand Down
2 changes: 1 addition & 1 deletion source/reference/crud.txt
Original file line number Diff line number Diff line change
Expand Up @@ -707,7 +707,7 @@ each declared field:
# => "Artem"

To use this mechanism, each field must be explicitly declared, or the
model class must enable :ref:`dynamic fields <dynamic-fields>`.
model class must enable :ref:`dynamic fields <mongoid-dynamic-fields>`.


Custom Getters & Setters
Expand Down
3 changes: 1 addition & 2 deletions source/reference/fields.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1251,8 +1251,7 @@ Then, use it your model class:
Note that the handler function will be invoked whenever the option is used
in the field definition, even if the option's value is false or nil.


.. _dynamic-fields:
.. _mongoid-dynamic-fields:

Dynamic Fields
==============
Expand Down
2 changes: 1 addition & 1 deletion source/tutorials/getting-started-rails6.txt
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ migrating from ActiveRecord to Mongoid.
ActiveRecord models derive from ``ApplicationRecord`` and do not have
column definitions. Mongoid models generally have no superclass but must
include ``Mongoid::Document``, and usually define the fields explicitly
(but :ref:`dynamic fields <dynamic-fields>` may also be used instead of
(but :ref:`dynamic fields <mongoid-dynamic-fields>` may also be used instead of
explicit field definitions).

For example, a bare-bones Post model may look like this in ActiveRecord:
Expand Down
2 changes: 1 addition & 1 deletion source/tutorials/getting-started-rails7.txt
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ migrating from ActiveRecord to Mongoid.
ActiveRecord models derive from ``ApplicationRecord`` and do not have
column definitions. Mongoid models generally have no superclass but must
include ``Mongoid::Document``, and usually define the fields explicitly
(but :ref:`dynamic fields <dynamic-fields>` may also be used instead of
(but :ref:`dynamic fields <mongoid-dynamic-fields>` may also be used instead of
explicit field definitions).

For example, a bare-bones Post model may look like this in ActiveRecord:
Expand Down
Loading