From 9175c0dc56e73bf2659566c07ff6c9af0832c9d7 Mon Sep 17 00:00:00 2001 From: rustagir Date: Wed, 15 Jan 2025 10:51:33 -0500 Subject: [PATCH] DOCSP-46213: bump to rails 8 and remove old tuts --- snooty.toml | 4 +- source/quick-start-rails.txt | 2 +- .../download-and-install.txt | 7 +- source/quick-start-rails/view-data.txt | 2 +- source/quick-start-sinatra.txt | 5 +- source/tutorials.txt | 10 - source/tutorials/documents.txt | 18 - source/tutorials/getting-started-rails6.txt | 551 ------------------ source/tutorials/getting-started-rails7.txt | 471 --------------- source/tutorials/getting-started-sinatra.txt | 220 ------- 10 files changed, 5 insertions(+), 1285 deletions(-) delete mode 100644 source/tutorials/documents.txt delete mode 100644 source/tutorials/getting-started-rails6.txt delete mode 100644 source/tutorials/getting-started-rails7.txt delete mode 100644 source/tutorials/getting-started-sinatra.txt diff --git a/snooty.toml b/snooty.toml index 8ea40b05..22980ad3 100644 --- a/snooty.toml +++ b/snooty.toml @@ -16,12 +16,10 @@ toc_landing_pages = [ ] [constants] -rails-6-version = 6.0 -rails-7-version = 7.1 rails-8-version-docs = "v8.0" odm = "Mongoid" version = "9.0" -full-version = "{+version+}.2" +full-version = "{+version+}.4" ruby-driver = "Ruby driver" language = "Ruby" quickstart-sinatra-app-name = "my-sinatra-app" diff --git a/source/quick-start-rails.txt b/source/quick-start-rails.txt index 60de78da..659820ca 100644 --- a/source/quick-start-rails.txt +++ b/source/quick-start-rails.txt @@ -20,7 +20,7 @@ Quick Start - Ruby on Rails Overview -------- -This guide shows you how to use {+odm+} in a new **Ruby on Rails 7 (Rails)** +This guide shows you how to use {+odm+} in a new **Ruby on Rails 8 (Rails)** web application, connect to a MongoDB cluster hosted on MongoDB Atlas, and perform read and write operations on the data in your cluster. diff --git a/source/quick-start-rails/download-and-install.txt b/source/quick-start-rails/download-and-install.txt index 9814fdbc..cca1e8af 100644 --- a/source/quick-start-rails/download-and-install.txt +++ b/source/quick-start-rails/download-and-install.txt @@ -14,7 +14,7 @@ Download and Install Prerequisites ------------- -To create the Quick Start application by using Ruby on Rails 7, you need the +To create the Quick Start application by using Ruby on Rails 8, you need the following software installed in your development environment: - `{+language+}. `__ @@ -24,11 +24,6 @@ following software installed in your development environment: - A terminal app and shell. For MacOS users, use Terminal or a similar app. For Windows users, use PowerShell. -.. tip:: Rails 6 Tutorial - - If you prefer to use Rails 6 to build your application, see the - :ref:`mongoid-getting-started-rails-6` guide. - Download and Install the {+odm+} and Framework Gems --------------------------------------------------- diff --git a/source/quick-start-rails/view-data.txt b/source/quick-start-rails/view-data.txt index 57ad2ef2..81f1355c 100644 --- a/source/quick-start-rails/view-data.txt +++ b/source/quick-start-rails/view-data.txt @@ -61,7 +61,7 @@ View MongoDB Data :copyable: false => Booting Puma - => Rails 7.2.1 application starting in development + => Rails 8.0.1 application starting in development => Run `bin/rails server --help` for more startup options Puma starting in single mode... * Puma version: 6.4.3 (ruby 3.2.5-p208) ("The Eagle of Durango") diff --git a/source/quick-start-sinatra.txt b/source/quick-start-sinatra.txt index e0e053fd..db7a785d 100644 --- a/source/quick-start-sinatra.txt +++ b/source/quick-start-sinatra.txt @@ -49,11 +49,8 @@ Follow the steps in this guide to create a sample {+odm+} web application that connects to a MongoDB deployment. .. tip:: Other Framework Tutorials - - If you prefer to use Ruby on Rails 6 to build your application, see the - :ref:`mongoid-getting-started-rails-6` guide. - If you prefer to use Ruby on Rails 7 as your web framework, see the + If you prefer to use Ruby on Rails 8 as your web framework, see the :ref:`mongoid-quick-start-rails` guide. .. TODO .. tip:: diff --git a/source/tutorials.txt b/source/tutorials.txt index 5c03cb90..8b30c6e0 100644 --- a/source/tutorials.txt +++ b/source/tutorials.txt @@ -4,15 +4,9 @@ Tutorials ********* -.. default-domain:: mongodb - .. toctree:: :titlesonly: - tutorials/getting-started-sinatra - tutorials/getting-started-rails7 - tutorials/getting-started-rails6 - tutorials/documents tutorials/common-errors tutorials/automatic-encryption @@ -21,9 +15,5 @@ Overview See the following sections to learn more about working with Mongoid: -- :ref:`Getting Started (Sinatra) ` -- :ref:`Getting Started (Rails 7) ` -- :ref:`Getting Started (Rails 6) ` -- :ref:`Documents ` - :ref:`Common Errors ` - :ref:`Automatic Client-Side Field Level Encryption ` \ No newline at end of file diff --git a/source/tutorials/documents.txt b/source/tutorials/documents.txt deleted file mode 100644 index 2bd87f30..00000000 --- a/source/tutorials/documents.txt +++ /dev/null @@ -1,18 +0,0 @@ -.. _documents: - -********* -Documents -********* - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Documents are the core objects in Mongoid and any object that is to be persisted to the -database must include ``Mongoid::Document``. The representation of a Document in MongoDB -is a BSON object that is very similar to a Ruby hash or JSON object. Documents can be stored -in their own collections in the database, or can be embedded in other Documents n levels deep. diff --git a/source/tutorials/getting-started-rails6.txt b/source/tutorials/getting-started-rails6.txt deleted file mode 100644 index 0b5e32bd..00000000 --- a/source/tutorials/getting-started-rails6.txt +++ /dev/null @@ -1,551 +0,0 @@ -.. _mongoid-getting-started-rails-6: - -========================= -Getting Started (Rails 6) -========================= - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -In this guide, you can learn how to implement {+odm} in a Ruby on Rails -6 web application. View the following sections to learn how to integrate -{+odm+} in new applications or how to add it to existing applications. - -.. note:: - - This tutorial is for Ruby on Rails 6. To use Ruby on Rails 7 as your - web framework, see the :ref:`mongoid-quick-start-rails` guide. - -New Application ---------------- - -This section shows how to create a new Ruby on Rails application using Mongoid -for data access. The application will be similar to the blog application -described in the `Ruby on Rails Getting Started -`__ -guide, however using Mongoid instead of ActiveRecord as the database adapter. - -The complete source code for this application can be found in the -`mongoid-demo GitHub repository. -`__ - -.. note:: - - This guide assumes basic familiarity with Ruby on Rails. - To learn more about Ruby on Rails, please refer to its `Getting Started - guide `__ or - other Rails guides. - -Install ``rails`` -~~~~~~~~~~~~~~~~~ - -We will use a Rails generator to create the application skeleton. -In order to do so, the first step is to install the ``rails`` gem: - -.. code-block:: sh - - gem install rails -v '~> {+rails-6-version+}' - - -Create New Application -~~~~~~~~~~~~~~~~~~~~~~ - -Use the ``rails`` command to create the application skeleton, as follows: - -.. code-block:: sh - - rails new blog --skip-active-record --skip-bundle - cd blog - -.. note:: - - You may receive a warning like this: - - .. code-block:: sh - - Could not find gem 'puma (~> 3.11)' in any of the gem sources listed in your Gemfile. - Run `bundle install` to install missing gems. - - Disregard it as we will be taking care of gem installation - in a moment. - -We pass ``--skip-active-record`` to request that ActiveRecord is not added -as a dependency, because we will be using Mongoid instead. Additionally -we pass ``--skip-bundle`` because we'll be modifying the ``Gemfile`` to -add the ``mongoid`` dependency. - -If you intend to test your application with RSpec, you can instruct the -generator to omit default Rails test setup by passing ``--skip-test`` -and ``--skip-system-test`` options: - -.. code-block:: sh - - rails new blog --skip-bundle --skip-active-record --skip-test --skip-system-test - cd blog - -Create Git Repo -~~~~~~~~~~~~~~~ - -While not required, we recommend creating a Git repository for your application: - -.. code-block:: sh - - git init . - git add . - git commit - -Commit your changes as you are following this tutorial. - -Add Mongoid -~~~~~~~~~~~ - -1. Modify the ``Gemfile`` to add a reference to the -`mongoid `_ gem: - -.. code-block:: ruby - :caption: Gemfile - - gem 'mongoid' - -.. note:: - - Mongoid 7.0.5 or higher is required to use Rails 6.0. - -2. Install gem dependencies: - -.. code-block:: sh - - bundle install - -3. Generate the default Mongoid configuration: - -.. code-block:: sh - - bin/rails g mongoid:config - -This generator will create the ``config/mongoid.yml`` configuration file -(used to configure the connection to the MongoDB deployment) and the -``config/initializers/mongoid.rb`` initializer file (which may be used for -other Mongoid-related configuration). Note that as we are not using -ActiveRecord we will not have a ``database.yml`` file. - -.. _run-locally: - -Run MongoDB Locally -~~~~~~~~~~~~~~~~~~~ - -The configuration created in the previous step is suitable when -a MongoDB server is running locally. If you do not already have a -local MongoDB server, `download and install MongoDB -`_. - -While the generated ``mongoid.yml`` will work without modifications, -we recommend reducing the server selection timeout for development. -With this change, the uncommented lines of ``mongoid.yml`` should look -like this: - -.. code-block:: none - - development: - clients: - default: - database: blog_development - hosts: - - localhost:27017 - options: - server_selection_timeout: 1 - - -.. _use-atlas: - -Use MongoDB Atlas -~~~~~~~~~~~~~~~~~ - -Instead of downloading, installing and running MongoDB locally, you can create -a free MongoDB Atlas account and create a `free MongoDB cluster in Atlas -`_. -Once the cluster is created, follow the instructions in `connect to the cluster -page `_ -to obtain the URI. Use the *Ruby driver 2.5 or later* format. - -Paste the URI into the ``config/mongoid.yml`` file, and comment out the -hosts that are defined. We recommend setting the server selection timeout to 5 -seconds for development environment when using Atlas. - -The uncommented contents of ``config/mongoid.yml`` should look like this: - -.. code-block:: yaml - - development: - clients: - default: - uri: mongodb+srv://user:pass@yourcluster.mongodb.net/blog_development?retryWrites=true&w=majority - options: - server_selection_timeout: 5 - -Other Rails Dependencies -~~~~~~~~~~~~~~~~~~~~~~~~ - -If this is the first Rails application you are creating, you may need to -install Node.js on your computer. This can be done via your operating system -packages or by `downloading a binary `_. - -Next, if you do not have Yarn installed, `follow its installation instructions -`_. - -Finally, install webpacker: - -.. code-block:: sh - - rails webpacker:install - - -Run Application -~~~~~~~~~~~~~~~ - -You can now start the application server by running: - -.. code-block:: sh - - rails s - -Access the application by navigating to `localhost:3000 -`_. - -Add Posts -~~~~~~~~~ - -Using the standard Rails scaffolding, Mongoid can generate the necessary -model, controller and view files for our blog so that we can quickly begin -creating blog posts: - -.. code-block:: sh - - bin/rails g scaffold Post title:string body:text - -Navigate to `localhost:3000/posts `_ -to create posts and see the posts that have already been created. - -.. figure:: ../img/rails-new-blog.png - :alt: Screenshot of the new blog - -Add Comments -~~~~~~~~~~~~ - -To make our application more interactive, let's add the ability for users to -add comments to our posts. - -Create the ``Comment`` model: - -.. code-block:: sh - - bin/rails g scaffold Comment name:string message:string post:belongs_to - -Open the ``Post`` model file, ``app/models/post.rb``, and add a ``has_many`` -association for the comments: - -.. 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 - end - -.. note:: - *The following is only required if using a version of Mongoid < 7.0.8 or 7.1.2 (see* - `MONGOID-4885 `_ *for details)* - - Open the ``Comment`` model file, ``app/models/comment.rb``, and change the - generated ``embedded_in`` association to ``belongs_to``: - - .. code-block:: ruby - :caption: app/models/comment.rb - - class Comment - include Mongoid::Document - - field :name, type: String - field :message, type: String - - belongs_to :post - end - -Open the post show view file, ``app/views/posts/show.html.erb``, and add -a section rendering existing comments and prompting to leave a new comment: - -.. code-block:: html - :caption: app/views/posts/show.html.erb - -
-
-

- <%= @post.comments.count %> Comments -

- <%= render @post.comments %> -
-
-

Leave a reply

- <%= render partial: 'comments/form', locals: { comment: @post.comments.build } %> -
-
-
- -Open the comment form file and change the type of field for ``:message`` -from ``text_field`` to ``text_area``, as well as the type of field for -``:post_id`` from ``text_field`` to ``hidden_field``. The result -should look like this: - -.. code-block:: html - :caption: app/views/comments/_form.html.erb - - <%= form_with(model: comment, local: true) do |form| %> - <% if comment.errors.any? %> -
-

<%= pluralize(comment.errors.count, "error") %> prohibited this comment from being saved:

- -
    - <% comment.errors.full_messages.each do |message| %> -
  • <%= message %>
  • - <% end %> -
-
- <% end %> - -
- <%= form.label :name %> - <%= form.text_field :name %> -
- -
- <%= form.label :message %> - <%= form.text_area :message %> -
- -
- <%= form.hidden_field :post_id %> -
- -
- <%= form.submit %> -
- <% end %> - -Create a partial for the comment view, ``app/views/comments/_comment.html.erb`` -with the following contents: - -.. code-block:: html - :caption: app/views/comments/_comment.html.erb - -

- <%= comment.name %>: - <%= comment.message %> -
- <%= link_to 'Delete', [comment], - method: :delete, - class: "button is-danger", - data: { confirm: 'Are you sure?' } %> -

- -You should now be able to leave comments for the posts: - -.. image:: ../img/rails-blog-new-comment.png - :alt: Screenshot of the blog with a new comment being added - -Existing Application --------------------- - -Follow these steps to switch an existing Ruby on Rails application to use -Mongoid instead of ActiveRecord. - -Dependencies -~~~~~~~~~~~~ - -Remove or comment out any RDBMS libraries like ``sqlite``, ``pg`` etc. -mentioned in ``Gemfile``, and add ``mongoid``: - -.. code-block:: ruby - :caption: Gemfile - - gem 'mongoid' - -.. note:: - - Mongoid 7.0.5 or higher is required to use Rails 6.0. - -Install gem dependencies: - -.. code-block:: sh - - bundle install - -Loaded Frameworks -~~~~~~~~~~~~~~~~~ - -Examine ``config/application.rb``. If it is requiring all components of Rails -via ``require 'rails/all'``, change it to require individual frameworks: - -.. code-block:: ruby - :caption: config/application.rb - - # Remove or comment out - #require "rails/all" - - # Add this require instead of "rails/all": - require "rails" - - # Pick the frameworks you want: - require "active_model/railtie" - require "active_job/railtie" - require "action_controller/railtie" - require "action_mailer/railtie" - # require "action_mailbox/engine" - # require "action_text/engine" - require "action_view/railtie" - require "action_cable/engine" - require "sprockets/railtie" - require "rails/test_unit/railtie" - - # Remove or comment out ActiveRecord and ActiveStorage: - # require "active_record/railtie" - # require "active_storage/engine" - -.. note:: - - At this time ActiveStorage requires ActiveRecord and is not usable with - Mongoid. - -ActiveRecord Configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Review all configuration files (``config/application.rb``, -``config/environments/{development,production.test}.rb``) and remove or -comment out any references to ``config.active_record`` and -``config.active_storage``. - -Stop Spring -~~~~~~~~~~~ - -If your application is using Spring, which is the default on Rails 6, -Spring must be stopped after changing dependencies or configuration. - -.. code-block:: sh - - ./bin/spring stop - -.. note:: - - Sometimes running ``./bin/spring stop`` claims to stop Spring, but does - not. Verify that all Spring processes are terminated before proceeding. - -.. note:: - - Sometimes Spring tries to load ActiveRecord even when the application - contains no ActiveRecord references. If this happens, add an ActiveRecord - adapter dependency such as ``sqlite3`` to your ``Gemfile`` so that - ActiveRecord may be completely loaded or remove Spring from your - application. - -Mongoid Configuration -~~~~~~~~~~~~~~~~~~~~~ - -Generate the default Mongoid configuration: - -.. code-block:: sh - - bin/rails g mongoid:config - -This generator will create the ``config/mongoid.yml`` configuration file -(used to configure the connection to the MongoDB deployment) and the -``config/initializers/mongoid.rb`` initializer file (which may be used for -other Mongoid-related configuration). In general, it is recommended to use -``mongoid.yml`` for all Mongoid configuration. - -Review the sections :ref:`Run MongoDB Locally ` and -:ref:`Use MongoDB Atlas ` to decide how you would like to deploy -MongoDB, and adjust Mongoid configuration (``config/mongoid.yml``) to match. - -Adjust Models -~~~~~~~~~~~~~ - -If your application already has models, these will need to be changed when -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 ` may also be used instead of -explicit field definitions). - -For example, a bare-bones Post model may look like this in ActiveRecord: - -.. code-block:: ruby - :caption: app/models/post.rb - - class Post < ApplicationRecord - has_many :comments, dependent: :destroy - end - -The same model may look like this in Mongoid: - -.. 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 - end - -Or like this with dynamic fields: - -.. code-block:: ruby - :caption: app/models/post.rb - - class Post - include Mongoid::Document - include Mongoid::Attributes::Dynamic - - has_many :comments, dependent: :destroy - end - -Mongoid does not utilize ActiveRecord migrations, since MongoDB does not -require a schema to be defined prior to storing data. - -Data Migration -~~~~~~~~~~~~~~ - -If you already have data in a relational database that you would like to -transfer to MongoDB, you will need to perform a data migration. As noted -above, no schema migration is necessary because MongoDB does not require -a predefined schema to store the data. - -The migration tools are often specific to the data being migrated because, -even though Mongoid supports a superset of ActiveRecord associations, -the way that model references are stored in collections differs between -Mongoid and ActiveRecord. With that said, MongoDB has -some resources on migrating from an RDBMS to MongoDB such as the -`RDBMS to MongoDB Migration Guide `_ and -`Modernization Guide `_. - -Rails API -~~~~~~~~~ - -The process for creating a Rails API application with Mongoid is the same -as when creating a regular application, with the only change being the -``--api`` parameter to ``rails new``. Migrating a Rails API application to -Mongoid follows the same process described above for regular Rails applications. - -A complete Rails API application similar to the one described in this tutorial -can be found in `the mongoid-demo GitHub repository -`_. diff --git a/source/tutorials/getting-started-rails7.txt b/source/tutorials/getting-started-rails7.txt deleted file mode 100644 index 9e7c282d..00000000 --- a/source/tutorials/getting-started-rails7.txt +++ /dev/null @@ -1,471 +0,0 @@ -.. _getting-started-7: - -************************* -Getting Started (Rails 7) -************************* - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -.. note:: - - This tutorial is for Ruby on Rails 7. If this is not the version - you're using, choose the appropriate tutorial for your Rails version - from the navigation menu. - -New Application -=============== - -This section demonstrates how to create a new Ruby on Rails application using the Mongoid ODM. -By replacing Rails' default `ActiveRecord `_ -adapter with MongoDB's ORM-like library for data access we will create an application similar to the -blog application described in the `Ruby on Rails Getting Started -`_ guide. - -The complete source code for this application can be found in the -`mongoid-demo GitHub repository -`_. - -.. note:: - - This guide assumes basic familiarity with Ruby on Rails. - To learn more about Ruby on Rails, please refer to its `Getting Started - guide `_ or - other Rails guides. - - -Install ``rails`` ------------------ - -We will use a Rails generator to create the application skeleton. -In order to do so, the first step is to install the ``rails`` gem: - -.. code-block:: sh - - gem install rails -v {+rails-7-version+} - - -Create New Application ----------------------- - -Use the ``rails`` command to create the application skeleton, as follows: - -.. code-block:: sh - - rails new blog --skip-active-record - cd blog - -We pass ``--skip-active-record`` to request that ActiveRecord is not added -as a dependency, because we will be using Mongoid instead. - -Optionally Skip Tests -````````````````````` - -If you intend to test your application with `RSpec `_, you can instruct the -generator to omit the default Rails test setup by passing ``--skip-test`` -and ``--skip-system-test`` options: - -.. code-block:: sh - - rails new blog --skip-active-record --skip-test --skip-system-test - cd blog - -Setup Mongoid -------------- - -1. Modify the ``Gemfile`` to add a reference to the -`mongoid `_ gem: - -.. code-block:: ruby - :caption: Gemfile - - gem 'mongoid' - -2. Install gem dependencies: - -.. code-block:: sh - - bundle install - -3. Generate the default `Mongoid configuration `_: - -.. code-block:: sh - - bin/rails g mongoid:config - -This generator will create the ``config/mongoid.yml`` configuration file -(used to configure the connection to the MongoDB deployment) and the -``config/initializers/mongoid.rb`` initializer file (which may be used for -other Mongoid-related configuration). Note that as we are not using -ActiveRecord we will not have a ``database.yml`` file. - - -.. _configure-self-managed: - -Configure for Self Managed MongoDB -`````````````````````````````````` - -The configuration created in the previous step is suitable when -a MongoDB server is running locally. If you do not already have a -local MongoDB server, `download and install MongoDB -`_. - -While the generated ``mongoid.yml`` will work without modifications, -we recommend reducing the server selection timeout for development. -With this change, the uncommented lines of ``mongoid.yml`` should look -like this: - -.. code-block:: yaml - - development: - clients: - default: - database: blog_development - hosts: - - localhost:27017 - options: - server_selection_timeout: 1 - - -.. _configure-atlas: - -Configure for MongoDB Atlas -``````````````````````````` - -Instead of downloading, installing and running MongoDB locally, you can create -a free MongoDB Atlas account and create a `free MongoDB cluster in Atlas -`_. -Once the cluster is created, follow the instructions in `connect to the cluster -page `_ -to obtain the URI. Use the *Ruby driver 2.5 or later* format. - -Paste the URI into the ``config/mongoid.yml`` file, and comment out the -hosts that are defined. We recommend setting the server selection timeout to 5 -seconds for development environment when using Atlas. - -The uncommented contents of ``config/mongoid.yml`` should look like this: - -.. code-block:: yaml - - development: - clients: - default: - uri: mongodb+srv://user:pass@yourcluster.mongodb.net/blog_development?retryWrites=true&w=majority - options: - server_selection_timeout: 5 - -Run Application ---------------- - -You can now start the application server by running: - -.. code-block:: sh - - bin/rails s - -Access the application by navigating to `localhost:3000 -`_. - - -Add Posts ---------- - -Using the standard Rails scaffolding, Mongoid can generate the necessary -model, controller and view files for our blog so that we can quickly begin -creating blog posts: - -.. code-block:: sh - - bin/rails g scaffold Post title:string body:text - -Navigate to `localhost:3000/posts `_ -to create posts and see the posts that have already been created. - -.. figure:: /img/rails-new-blog.png - :alt: Screenshot of the new blog - - -Add Comments ------------- - -To make our application more interactive, let's add the ability for users to -add comments to our posts. - -Create the ``Comment`` model: - -.. code-block:: sh - - bin/rails g scaffold Comment name:string message:string post:belongs_to - -Open the ``Post`` model file, ``app/models/post.rb``, and add a ``has_many`` -association for the comments: - -.. code-block:: ruby - :caption: app/models/post.rb - - class Post - include Mongoid::Document - include Mongoid::Timestamps - field :title, type: String - field :body, type: String - - has_many :comments, dependent: :destroy - end - -Open ``app/views/posts/show.html.erb`` and add -a section rendering existing comments and prompting to leave a new comment: - -.. code-block:: erb - :caption: app/views/posts/show.html.erb - -
-
-

- <%= @post.comments.count %> Comments -

- <%= render @post.comments %> -
-
-

Leave a reply

- <%= render partial: 'comments/form', locals: { comment: @post.comments.build } %> -
-
-
- -Open ``app/views/comments/_form.html.erb`` and change the type of field for ``:message`` -from ``text_field`` to ``text_area``, as well as the type of field for -``:post_id`` from ``text_field`` to ``hidden_field``. The result -should look like this: - -.. code-block:: erb - :caption: app/views/comments/_form.html.erb - - <%= form_with(model: comment, local: true) do |form| %> - <% if comment.errors.any? %> -
-

<%= pluralize(comment.errors.count, "error") %> prohibited this comment from being saved:

- -
    - <% comment.errors.full_messages.each do |message| %> -
  • <%= message %>
  • - <% end %> -
-
- <% end %> - -
- <%= form.label :name %> - <%= form.text_field :name %> -
- -
- <%= form.label :message %> - <%= form.text_area :message %> -
- -
- <%= form.hidden_field :post_id %> -
- -
- <%= form.submit %> -
- <% end %> - -Next replace ``app/view/comments/_comment.html.erb`` with the following contents: - -.. code-block:: erb - :caption: app/views/comments/_comment.html.erb - -

- <%= comment.name %>: - <%= comment.message %> - <%= link_to 'Delete', [comment], - data: { - "turbo-method": :delete, - "turbo-confirm": 'Are you sure?' - } %> -

- - -You should now be able to leave comments for the posts: - -.. figure:: /img/rails-blog-new-comment.png - :alt: Screenshot of the blog with a new comment being added - - -Existing Application -==================== - -Mongoid can be easily added to an existing Rails application and run alongside other ActiveRecord -adapters. If this is your use case, updating dependencies and populating the configuration file will -allow you to start using MongoDB within your application. - -To switch an existing Ruby on Rails application to use Mongoid instead of ActiveRecord additional -configuration changes will be required, as described below. - -Dependencies ------------- - -First, the ``mongoid`` gem will need to be added your ``Gemfile``. - -.. code-block:: ruby - :caption: Gemfile - - gem 'mongoid' - -If Mongoid will be the **only** database adapter, remove or comment out any RDBMS libraries -like ``sqlite`` or ``pg`` mentioned in the ``Gemfile``. - -Install gem dependencies: - -.. code-block:: sh - - bundle install - -Mongoid Configuration ---------------------- - -Generate the default Mongoid configuration: - -.. code-block:: sh - - bin/rails g mongoid:config - -This generator will create the ``config/mongoid.yml`` configuration file -(used to configure the connection to the MongoDB deployment) and the -``config/initializers/mongoid.rb`` initializer file (which may be used for -other Mongoid-related configuration). In general, it is recommended to use -``mongoid.yml`` for all Mongoid configuration. - -Review the sections :ref:`Configure for Self Managed MongoDB ` -and :ref:`Configure for MongoDB Atlas ` to decide how you -would like to deploy MongoDB, and adjust the Mongoid configuration -(``config/mongoid.yml``) to match. - -Loaded Frameworks ------------------ - -Examine ``config/application.rb``. If it is requiring all components of Rails -via ``require 'rails/all'``, change it to require individual frameworks. To verify the contents of -``rails/all`` for your version see the `Github Repository -`_: - -.. code-block:: ruby - :caption: config/application.rb - - # Remove or comment out - #require "rails/all" - - # Add the following instead of "rails/all": - require "rails" - - # 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 - -.. warning:: - - Due to their reliance on ActiveRecord, `ActionText `_, - `ActiveStorage `_ and - `ActionMailbox `_ cannot be used - with Mongoid. - -ActiveRecord Configuration --------------------------- - -Review all configuration files (``config/application.rb``, -``config/environments/{development,production.test}.rb``) and remove or -comment out any references to ``config.active_record`` and -``config.active_storage``. - -Adjust Models -------------- - -If your application already has models, these will need to be changed when -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 ` may also be used instead of -explicit field definitions). - -For example, a bare-bones Post model may look like this in ActiveRecord: - -.. code-block:: ruby - :caption: app/models/post.rb - - class Post < ApplicationRecord - has_many :comments, dependent: :destroy - end - -The same model may look like this in Mongoid: - -.. 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 - end - -Or like this with dynamic fields: - -.. code-block:: ruby - :caption: app/models/post.rb - - class Post - include Mongoid::Document - include Mongoid::Attributes::Dynamic - - has_many :comments, dependent: :destroy - end - -Mongoid does not utilize ActiveRecord migrations, since MongoDB does not -require a schema to be defined prior to storing data. - -Data Migration --------------- - -If you already have data in a relational database that you would like to -transfer to MongoDB, you will need to perform a data migration. As noted -above, no schema migration is necessary because MongoDB does not require -a predefined schema to store the data. - -The migration tools are often specific to the data being migrated because, -even though Mongoid supports a superset of ActiveRecord associations, -the way that model references are stored in collections differs between -Mongoid and ActiveRecord. With that said, MongoDB has -some resources on migrating from an RDBMS to MongoDB such as the -`RDBMS to MongoDB Migration Guide `_ and -`Modernization Guide `_. - - -Rails API ---------- - -The process for creating a Rails API application with Mongoid is the same -as when creating a regular application, with the only change being the -``--api`` parameter to ``rails new``. Migrating a Rails API application to -Mongoid follows the same process described above for regular Rails applications. - -A complete Rails API application similar to the one described in this tutorial -can be found in `the mongoid-demo GitHub repository -`_. diff --git a/source/tutorials/getting-started-sinatra.txt b/source/tutorials/getting-started-sinatra.txt deleted file mode 100644 index 832dd0d6..00000000 --- a/source/tutorials/getting-started-sinatra.txt +++ /dev/null @@ -1,220 +0,0 @@ -.. _getting-started-sinatra: - -************************* -Getting Started (Sinatra) -************************* - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - - -New Application -=============== - -This section shows how to create a new Sinatra application using Mongoid -for data access. The process is similar for other Ruby applications not -using Ruby on Rails. - -The complete source code for this application is available `in the -mongoid-demo GitHub repository -`_. - -Create Git Repo ---------------- - -While not required, we recommend creating a Git repository for your application: - -.. code-block:: sh - - git init blog - cd blog - -Commit your changes as you are following this tutorial. - - -Create Gemfile --------------- - -Create a file named ``Gemfile`` with the following contents: - -.. code-block:: ruby - - source 'https://rubygems.org' - - gem 'sinatra' - gem 'mongoid' - gem 'puma' - - -Install Dependencies --------------------- - -Run the following commands to install the dependencies: - -.. code-block:: sh - - gem install bundler - bundle install - -This command will generate a file named ``Gemfile.lock`` which we recommend -committing to your Git repository. - - -Run MongoDB Locally -------------------- - -To develop locally with MongoDB, `download and install MongoDB -`_. - -Once MongoDB is installed and running, create a file named ``config/mongoid.yml`` -pointing to your deployment. For example, if you launched a standalone -``mongod`` on the default port, the following contents would be appropriate: - -.. code-block:: none - - development: - clients: - default: - database: blog_development - hosts: - - localhost:27017 - options: - server_selection_timeout: 1 - - -Use MongoDB Atlas ------------------ - -Instead of downloading, installing and running MongoDB locally, you can create -a free MongoDB Atlas account and create a `free MongoDB cluster in Atlas -`_. -Once the cluster is created, follow the instructions in `connect to the cluster -page `_ -to obtain the URI. Use the *Ruby driver 2.5 or later* format. - -Create a file named ``config/mongoid.yml`` with the following -contents, replacing the URI with the actual URI for your cluster: - -.. code-block:: yaml - - development: - clients: - default: - uri: mongodb+srv://user:pass@yourcluster.mongodb.net/blog_development?retryWrites=true&w=majority - options: - server_selection_timeout: 5 - - - -Basic Application ------------------ - -Create a file named ``app.rb`` with the following contents. First, some -requires: - -.. code-block:: ruby - - require 'sinatra' - require 'mongoid' - -Load the Mongoid configuration file and configure Mongoid. This is done -automatically when Mongoid is used with Rails, but since we are using Mongoid -with Sinatra, we need to do this ourselves: - -.. code-block:: ruby - - Mongoid.load!(File.join(File.dirname(__FILE__), 'config', 'mongoid.yml')) - -Now we can define some models: - -.. code-block:: ruby - - class Post - include Mongoid::Document - - field :title, type: String - field :body, type: String - - has_many :comments - end - - class Comment - include Mongoid::Document - - field :name, type: String - field :message, type: String - - belongs_to :post - end - -... and add some routes: - -.. code-block:: ruby - - get '/posts' do - Post.all.to_json - end - - post '/posts' do - post = Post.create!(params[:post]) - post.to_json - end - - get '/posts/:post_id' do |post_id| - post = Post.find(post_id) - post.attributes.merge( - comments: post.comments, - ).to_json - end - - post '/posts/:post_id/comments' do |post_id| - post = Post.find(post_id) - comment = post.comments.create!(params[:comment]) - {}.to_json - end - - -Run Application -=============== - -Launch the application: - -.. code-block:: sh - - bundle exec ruby app.rb - -Try some requests via curl: - -.. code-block:: sh - - curl http://localhost:4567/posts - # => [] - - curl -d 'post[title]=hello&post[body]=hello+world' http://localhost:4567/posts - # => {"_id":{"$oid":"5d8151ec96fb4f0ed5a7a03f"},"body":"hello world","title":"hello"} - - curl http://localhost:4567/posts - # => [{"_id":{"_id":{"$oid":"5d8151ec96fb4f0ed5a7a03f"},"body":"hello world","title":"hello"}] - - curl -d 'comment[name]=David&comment[message]=I+like' http://localhost:4567/posts/5d8151ec96fb4f0ed5a7a03f/comments - # => {} - - curl http://localhost:4567/posts/5d8151ec96fb4f0ed5a7a03f - # => {"_id":{"$oid":"5d8151ec96fb4f0ed5a7a03f"},"title":"hello","body":"hello world","comments":[{"_id":{"$oid":"5d8157ac96fb4f20c5e45c4d"},"message":"I like","name":"David","post_id":{"$oid":"5d8151ec96fb4f0ed5a7a03f"}}]} - - -Existing Application -==================== - -To start using Mongoid in an existing Sinatra applications, the steps are -essentially the same as the one given above for a new application: - -1. Add the ``mongoid`` dependency to the ``Gemfile``. -2. Create a ``mongoid.yml`` configuration file. -3. Load the configuration file and configure Mongoid in the application. -4. Define Mongoid models.