首页 > 解决方案 > 在 Mongoid 中更新模型模式

问题描述

我有一个 API 模式下的 Ruby On Rails 应用程序并使用 Mongoid。这是我的模型:

class Posts
  include Mongoid::Document
  field :title        ,  type: String
  field :created_at   ,  type: Time , default: Time.now
end

现在过了一段时间,在 Post 集合中有很多记录,从现在开始,我需要"body"在模型中添加一个字段,如下所示:

class Posts
  include Mongoid::Document
  field :title        ,  type: String
  field :body         ,  type: String
  field :created_at   ,  type: Time , default: Time.now
end

问题是,应用程序仍然不理解这种变化!我没有使用 Rails 的内置 SQL 数据库,"db"我的应用程序中没有文件夹,因为它的 API 模式和使用 Mongoid。所以我不能使用命令rails db:migrate 那么如何在 Rails 应用程序中更新 Mongoid 模型?

还有一个问题是我怎样才能无模式地使用它?我只是定义模型的名称而不定义任何字段。并且添加功能,只需传递新记录的 JSON 对象并将其作为无模式模型使用。

标签: ruby-on-railsschemamongoid

解决方案


MongoDB 不需要 ActiveRecord 的迁移功能。您可以随时向模型添加字段并在应用程序的其余部分开始使用它。在现有文档中,该字段的值为nil.

要使用字段而不明确定义它们,请使用 Mongoid 的动态字段功能:https ://docs.mongodb.com/mongoid/master/tutorials/mongoid-documents/#dynamic-fields


推荐阅读