eduardo Uchida
eduardo Uchida

Reputation: 323

Create Model (RAILS) for mongoid

I have to connect my Rails app to MongoDB, after some research i found a gem (mongoid). My doubt is, how to create the model? The collection on MongoDB looks like the example bellow:

{
    "_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
}

Upvotes: 1

Views: 6238

Answers (3)

Abhilash Reddy
Abhilash Reddy

Reputation: 1549

It's the same way..

rails generate model model_name

Also, you can specify the orm:

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

And the model file will look something like this:

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

Upvotes: 7

Tushar Niras
Tushar Niras

Reputation: 3863

-> Create Model

rails generate model modelname

-> If data fields will different (dynamic) for each record, you need to add following line to your model

 include Mongoid::Attributes::Dynamic

->Create Record

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

Upvotes: 2

take
take

Reputation: 319

You would need to create a model in the app/models folder. For your example, it looks like it would be:

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

where SingularCollectionName is the collection name without pluralization.

You can read more here.

Upvotes: 1

Related Questions