【问题标题】:Create Model (RAILS) for mongoid为 mongoid 创建模型 (RAILS)
【发布时间】:2016-05-04 22:02:12
【问题描述】:

我必须将我的 Rails 应用程序连接到 MongoDB,经过一番研究,我发现了一个 gem (mongoid)。 我的疑问是,如何创建模型? MongoDB 上的集合类似于下面的示例:

{
    "_id": {
        "$oid": "56fbf7e577550f39a5aea04a"
    },
    "id_test": "225|1",
    "array_ex1": [],
    "array_ex2": [
        "obj_ex1": {
            "field_obj_1": "text1",
            "field_obj_2": "text2",
            "field_obj_3": "text3",
         }
     ],
    "obj_ex2": {
       "field1: "textex1",
       "field2: "textex2",
       "field3: "textex3",
    },
    "flg_test": true
}

【问题讨论】:

  • 你为什么不去看看 gem 的文档呢?

标签: ruby-on-rails ruby mongodb mongoid


【解决方案1】:

都是一样的。

rails generate model model_name

另外,你可以指定orm:

rails g active_record:model model_name
rails g mongoid:model model_name

模型文件看起来像这样:

class SomeModel
  include Mongoid::Document
  include Mongoid::Timestamps

  field :id_test, type: String
  field :array_ex1, type: Array
  field :array_ex2, type: Array
  field :obj_ex2
  field :flg_test, type: Boolean
end

【讨论】:

  • 如果我们使用两个数据库怎么办? sqllite 和 Mongo
【解决方案2】:

-> 创建模型

rails generate model modelname

-> 如果每条记录的数据字段不同(动态),则需要在模型中添加以下行

 include Mongoid::Attributes::Dynamic

->创建记录

modelname.create({:field1 "valie1", :field2 "value2"})
modelname.create({:field1 "valie1"})

【讨论】:

    【解决方案3】:

    您需要在app/models 文件夹中创建一个模型。对于您的示例,它看起来像:

    app/models/singular_collection_name.rb

    class SingularCollectionName
      include Mongoid::Document
    
      field :id_test, type: String
      field :array_ex1, type: Array
      field :array_ex2, type: Array
      field :obj_ex2, type: Hash
      field :flg_test, type: Boolean
    
    end
    

    其中 SingularCollectionName 是不带复数形式的集合名称。

    您可以阅读更多here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 1970-01-01
      相关资源
      最近更新 更多