Last active
October 25, 2018 09:02
-
-
Save snmmaurya/998aacfda3af8963264b686b4e9fcdd8 to your computer and use it in GitHub Desktop.
rails mongodb implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
References: https://github.com/mongodb/mongoid | |
mongoid is one of the best ODMs | |
Install mongodb - Reference: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/ | |
Ruby and Ruby on Rails version- | |
Rails - 5+ | |
Ruby - 2.5+ | |
Steps to start with mongoid - | |
Gemfile | |
gem 'mongoid' | |
Configuration | |
rails g mongoid:config | |
this command will create a file config/mongoid.yml | |
add following line into application.rb | |
Mongoid.load! "./config/mongoid.yml" | |
# defines mongodb configraion just like database.yml | |
Change inside mongoid.yml | |
specify database name and related credentials | |
mongodb by default run on port: 27017 | |
An example with model user | |
Create your model under app/models - user.rb | |
------------------ | |
class Role | |
include Mongoid::Document | |
field :name, type: String, default: "" | |
# index on name | |
index({ name: 1 }, {name: "role_name_index" }) | |
end | |
------------------ | |
------------------ | |
class User | |
include Mongoid::Document | |
field :balance, type: BigDecimal, default: 0.0 | |
field :age, type: Integer, default: 0 | |
field :name, type: String, default: 0 | |
field :data, type: Hash, default: {} | |
# association | |
belongs_to :role | |
# index on role_id | |
index({ role_id: 1 }, {name: "user_role_index" }) | |
end | |
------------------ | |
belongs_to :role | |
if you define association it will automatically creates associationName_id (ex: role_id) | |
index({ role_id: 1 }, {name: "user_role_index" }) | |
Adding index on role_id in ascending order | |
The collection would be created if does not exist - (pluralized and camle case version of model name - (users)) at the time of any operation like create / update. | |
Some readymade rake jobs | |
How to create index | |
rake db:mongoid:create_indexes | |
How to remove index | |
rake db:mongoid:remove_indexes | |
Finally create indexes | |
rake db:mongoid:create_indexes | |
now its ready - | |
rails console | |
> Role.create(name: 'admin') | |
> User.create({name: 'cherry', age: 28, balance: 10.34, data: {}.to_json, role: Role.find_by(name: 'admin')}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment