1

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
}
1
  • Why don't you go and check the gem's documentation? Commented Apr 20, 2017 at 11:15

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

what if we are using two databases ? sqllite and Mongo
2

-> 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"})

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.