升级Rails至5.0(MongoDB数据库):是否需创建application_record.rb?
Great question! Let’s break this down clearly, since Mongoid’s model structure works quite differently from ActiveRecord’s.
First, the straight answer: No, you don’t need to create an application_record.rb file or have your models inherit from a base class like you would with ActiveRecord. Here’s why:
- ActiveRecord in Rails 5 introduced
ApplicationRecordas a universal base class (inheriting fromActiveRecord::Base) to centralize shared model logic, callbacks, or configuration. This relies on class inheritance as the core way to pass down ORM functionality. - Mongoid, by contrast, uses module inclusion (via
include Mongoid::Document) to add database capabilities to your plain Ruby model classes. There’s no equivalent "base class" likeApplicationRecordin Mongoid’s design—its functionality is injected, not inherited.
That said, if you want to share common logic, configuration, or behavior across all your Mongoid models (similar to the goal of ApplicationRecord), there’s a Mongoid-friendly way to do it: use a custom concern module.
Example: Creating a shared Mongoid concern
You can build a concern that wraps Mongoid::Document plus any shared code, then include this concern in all your models:
# app/models/concerns/base_mongoid_document.rb module BaseMongoidDocument extend ActiveSupport::Concern included do # Core Mongoid functionality include Mongoid::Document # Add shared configuration here include Mongoid::Timestamps field :deleted_at, type: Time scope :active, -> { where(deleted_at: nil) } end # Shared instance methods def soft_delete update(deleted_at: Time.current) end end
Then in your model classes:
# app/models/user.rb class User include BaseMongoidDocument # Model-specific fields and logic field :name, type: String field :email, type: String end
This keeps your shared logic organized without forcing a class inheritance structure that doesn’t fit Mongoid’s design.
To recap: Skip the ApplicationRecord pattern for Mongoid—stick with module inclusion, and use concerns if you need to share code across models.
内容的提问来源于stack exchange,提问作者rAzOr

