入门(Rails 6)
本页内容
注意
本教程适用于 Ruby on Rails 6。如果这不是您使用的版本,请从导航菜单中选择您 Rails 版本的相应教程。
新应用
本节展示了如何使用 Mongoid 数据访问创建新的 Ruby on Rails 应用程序。该应用程序将与指南中描述的博客应用程序类似,但使用 Mongoid 而不是 ActiveRecord 作为数据库适配器。Ruby on Rails 入门指南中的
本应用程序的完整源代码可在mongoid-demo GitHub 仓库中找到。
注意
本指南假定您对 Ruby on Rails 基本熟悉。要了解 Ruby on Rails 的更多信息,请参阅其入门指南或其他 Rails 指南。
安装rails
我们将使用 Rails 生成器来创建应用程序骨架。为此,第一步是安装rails
软件包。
gem install rails -v '~> 6.0'
创建新应用程序
使用 rails
命令创建应用程序骨架,如下所示
rails new blog --skip-active-record --skip-bundle cd blog
注意
您可能会收到类似这样的警告
Could not find gem 'puma (~> 3.11)' in any of the gem sources listed in your Gemfile. Run `bundle install` to install missing gems.
请忽略它,因为我们将在稍后处理gem安装。
我们传递 --skip-active-record
以请求不将ActiveRecord添加为依赖项,因为我们将使用Mongoid。此外,我们还传递 --skip-bundle
,因为我们将修改 Gemfile
以添加 mongoid
依赖项。
如果您打算使用RSpec测试您的应用程序,您可以指示生成器通过传递 --skip-test
和 --skip-system-test
选项省略默认的Rails测试设置
rails new blog --skip-bundle --skip-active-record --skip-test --skip-system-test cd blog
创建Git仓库
虽然不是必需的,但我们建议为您的应用程序创建一个Git仓库
git init . git add . git commit
在遵循本教程的过程中,请提交您的更改。
添加Mongoid
1. 修改 Gemfile
文件,添加对 mongoid 钥石的引用
gem 'mongoid'
注意
使用 Rails 6.0 需要 Mongoid 7.0.5 或更高版本。
安装宝石依赖
bundle install
生成默认的 Mongoid 配置
bin/rails g mongoid:config
此生成器将创建 config/mongoid.yml
配置文件(用于配置连接到 MongoDB 部署),以及 config/initializers/mongoid.rb
初始化器文件(可能用于其他 Mongoid 相关配置)。注意,因为我们不使用 ActiveRecord,所以不会有 database.yml
文件。
在本地运行 MongoDB
上一步骤中创建的配置适用于本地运行 MongoDB 服务器的情况。如果您还没有本地 MongoDB 服务器,请 下载并安装 MongoDB。
虽然生成的 mongoid.yml
不修改即可使用,但我们建议减少开发时的服务器选择超时。此更改后,mongoid.yml
的未注释行应如下所示
development: clients: default: database: blog_development hosts: - localhost:27017 options: server_selection_timeout: 1
使用 MongoDB Atlas
您不必在本地下载、安装和运行MongoDB,而是可以创建一个免费的MongoDB Atlas账户,并在Atlas中创建一个免费的MongoDB集群。一旦集群创建完成,请按照连接到集群页面中的说明操作以获取URI。使用Ruby驱动程序2.5或更高版本格式。
将URI粘贴到config/mongoid.yml
文件中,并注释掉已定义的主机。我们建议在开发环境中使用Atlas时,将服务器选择超时设置为5秒。
config/mongoid.yml
中取消注释的内容应如下所示
development: clients: default: uri: mongodb+srv://user:pass@yourcluster.mongodb.net/blog_development?retryWrites=true&w=majority options: server_selection_timeout: 5
其他Rails依赖项
如果您正在创建第一个Rails应用程序,您可能需要在计算机上安装Node.js。这可以通过操作系统包或通过下载二进制文件来完成。
接下来,如果您还没有安装 Yarn,请按照其安装说明操作。
最后,安装webpacker
rails webpacker:install
运行应用程序
您现在可以通过运行以下命令启动应用程序服务器
rails s
通过导航到localhost:3000来访问应用程序。
添加帖子
使用标准的Rails脚手架,Mongoid可以为我们生成必要的模型、控制器和视图文件,以便我们快速开始创建博客帖子。
bin/rails g scaffold Post title:string body:text
导航到 localhost:3000/posts 来创建帖子并查看已创建的帖子。

添加评论
为了让我们的应用程序更具交互性,让我们添加用户可以添加评论到我们的帖子功能。
创建 Comment
模型
bin/rails g scaffold Comment name:string message:string post:belongs_to
打开 Post
模型文件,app/models/post.rb
,并为评论添加一个 has_many
关联
class Post include Mongoid::Document field :title, type: String field :body, type: String has_many :comments, dependent: :destroy end
注意
以下内容仅在您使用Mongoid版本低于7.0.8或7.1.2时需要(请参阅 MONGOID-4885 以获取详细信息)
打开Comment
模型文件,app/models/comment.rb
,并将生成的embedded_in
关联更改为belongs_to
class Comment include Mongoid::Document field :name, type: String field :message, type: String belongs_to :post end
打开文章展示视图文件,app/views/posts/show.html.erb
,并添加一个显示现有评论并提示留下新评论的部分
<section class="section comments"> <div class="container"> <h2 class="subtitle is-5"> <strong><%= @post.comments.count %></strong> Comments </h2> <%= render @post.comments %> <div class="comment-form"> <hr /> <h3 class="subtitle is-3">Leave a reply</h3> <%= render partial: 'comments/form', locals: { comment: @post.comments.build } %> </div> </div> </section>
打开评论表单文件,并将:message
字段的类型从text_field
更改为text_area
,同时将:post_id
字段的类型从text_field
更改为hidden_field
。结果应如下所示
<%= form_with(model: comment, local: true) do |form| %> <% if comment.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(comment.errors.count, "error") %> prohibited this comment from being saved:</h2> <ul> <% comment.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= form.label :name %> <%= form.text_field :name %> </div> <div class="field"> <%= form.label :message %> <%= form.text_area :message %> </div> <div class="field"> <%= form.hidden_field :post_id %> </div> <div class="actions"> <%= form.submit %> </div> <% end %>
创建一个用于评论视图的局部视图,app/views/comments/_comment.html.erb
,内容如下
<p> <strong><%= comment.name %>:</strong> <%= comment.message %> <br> <%= link_to 'Delete', [comment], method: :delete, class: "button is-danger", data: { confirm: 'Are you sure?' } %> </p>
现在您可以为文章留下评论了

现有应用
按照以下步骤将现有的Ruby on Rails应用程序切换为使用Mongoid而不是ActiveRecord。
依赖项
从 Gemfile
中删除或注释掉任何提到的 RDBMS 库,例如 sqlite
、pg
等,并添加 mongoid
gem 'mongoid'
注意
使用 Rails 6.0 需要 Mongoid 7.0.5 或更高版本。
安装宝石依赖
bundle install
已加载的框架
检查 config/application.rb
。如果它是通过 require 'rails/all'
调用 Rails 的所有组件,请将其更改为调用单独的框架
# 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"
注意
在此阶段,ActiveStorage 需要 ActiveRecord,并且不能与 Mongoid 一起使用。
ActiveRecord 配置
审查所有配置文件(config/application.rb
、config/environments/{development,production.test}.rb
)并删除或注释掉对 config.active_record
和 config.active_storage
的任何引用。
停止 Spring
如果您的应用程序使用 Spring(Rails 6 的默认选项),则在更改依赖项或配置后必须停止 Spring。
./bin/spring stop
注意
有时运行 ./bin/spring stop
声称停止了 Spring,但实际上并没有。在继续之前,请确保所有 Spring 进程都已终止。
注意
有时即使应用程序中没有 ActiveRecord 引用,Spring 也试图加载 ActiveRecord。如果发生这种情况,请在 Gemfile
中添加 ActiveRecord 适配器依赖项,例如 sqlite3
,以便完全加载 ActiveRecord,或者从应用程序中删除 Spring。
配置 Mongoid
生成默认的 Mongoid 配置
bin/rails g mongoid:config
此生成器将创建配置文件 config/mongoid.yml
(用于配置连接到 MongoDB 部署)和初始化文件 config/initializers/mongoid.rb
(可能用于其他 Mongoid 相关配置)。通常,建议对所有 Mongoid 配置使用 mongoid.yml
。
请查看部分 本地运行 MongoDB 和 使用 MongoDB Atlas,以确定您希望如何部署 MongoDB,并调整 Mongoid 配置(config/mongoid.yml
)以匹配。
调整模型
如果您的应用程序已经存在模型,则在从 ActiveRecord 迁移到 Mongoid 时需要更改这些模型。
ActiveRecord 模型从 ApplicationRecord
继承,并且没有列定义。Mongoid 模型通常没有超类,但必须包含 Mongoid::Document
,并且通常明确定义字段(但也可以使用动态字段代替显式字段定义)。
例如,一个简单的 Post 模型在 ActiveRecord 中的样子可能如下所示
class Post < ApplicationRecord has_many :comments, dependent: :destroy end
相同的模型在 Mongoid 中的样子可能如下所示
class Post include Mongoid::Document field :title, type: String field :body, type: String has_many :comments, dependent: :destroy end
或者使用动态字段的样子
class Post include Mongoid::Document include Mongoid::Attributes::Dynamic has_many :comments, dependent: :destroy end
Mongoid 不使用 ActiveRecord 迁移,因为 MongoDB 在存储数据之前不需要定义架构。
数据迁移
如果您已经有一个关系型数据库中的数据,希望将其转移到MongoDB,您需要进行数据迁移。如上所述,不需要进行模式迁移,因为MongoDB不需要预定义的模式来存储数据。
迁移工具通常针对要迁移的数据而特定,因为尽管Mongoid支持ActiveRecord关联的超集,但模型引用在集合中存储的方式在Mongoid和ActiveRecord之间不同。话虽如此,MongoDB有一些资源可供从RDBMS迁移到MongoDB,例如RDBMS到MongoDB迁移指南和现代化指南。
Rails API
使用Mongoid创建Rails API应用程序的过程与创建常规应用程序的过程相同,唯一的区别是--api
参数到rails new
。将Rails API应用程序迁移到Mongoid遵循上述常规Rails应用程序的相同过程。
与本文教程中描述的类似,可以在mongoid-demo GitHub 仓库中找到完整的 Rails API 应用程序。