Leon's Blogging

Coding blogging for hackers.

Rails With mongoDB

| Comments

Version: Ruby 2.5.3, Rails 5.2.2

Generate new project

1
rails new demo_rails_mongodb --skip-active-record --api -C

Add mongoid gem

1
gem 'mongoid', '~> 7.0.2'

create config/mongoid.yml

1
rails g mongoid:config

Add docker-compose

1
2
3
4
5
6
7
8
9
10
11
# docker-compose.yml
version: '3'
services:
  mongo:
    image: mongo:4.1
    container_name: mongo4
    restart: always
    ports:
      - '27017:27017'
    volumes:
      - ./tmp/data/mongo/data:/data/db
1
docker-compose up

Create model & data

Scaffold

1
rails generate scaffold book title:string author:string pages:integer
1
2
3
4
5
6
7
8
# app/models/book.rb
class Book
  include Mongoid::Document
  field :title, type: String
  field :pages, type: Integer
  field :author, type: String
  validates_presence_of :author
end
1
2
# rails c
Book.create(title: "First", pages:20, author:"leon")

View

1
2
# rails s -p 4321
http://localhost:4321/books

Demo

Reference

Comments