ruby-on-rails - 在 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 对象并将其作为无模式模型使用。
解决方案
MongoDB 不需要 ActiveRecord 的迁移功能。您可以随时向模型添加字段并在应用程序的其余部分开始使用它。在现有文档中,该字段的值为nil
.
要使用字段而不明确定义它们,请使用 Mongoid 的动态字段功能:https ://docs.mongodb.com/mongoid/master/tutorials/mongoid-documents/#dynamic-fields
推荐阅读
- spring - 如何测试 Spring 事务
- javascript - 加载 gif 直到页面完全加载
- linux - 我可以捕获我启动的另一个进程的输出吗?
- python - matplotlib set_major_formatter 创建 2 个图
- redis - @EnableRedisRepositories - 在 Spring Data Redis 中有什么用?
- asp.net-mvc - ASP.NET MVC 应用程序池不适用于部署
- oracle - 在 oracle 中插入选择失败
- windows - 如何使用 PowerShell 判断是 SAN 还是本地磁盘存储类型?
- matlab - 构造一个形成链的递归,直到不能添加新元素
- android - 在框架布局顶部添加按钮