-
Notifications
You must be signed in to change notification settings - Fork 9
Home
brew install mongodb
mongod --config /usr/local/etc/mongod.conf &
rails new mongodb-crud --skip-active-record
In Gemfile: gem 'mongoid', '~> 5.1.0'
bundle install
rails g mongoid:config
In Gemfile:
gem 'bootstrap-sass', '~> 3.3.6'
gem 'bootstrap-generators', '~> 3.3.4'
In app/assets/stylesheets/application.scss:
@import "bootstrap-variables";
@import "bootstrap-generators";
@import "bootstrap-sprockets";
@import "bootstrap";
In app/assets/javascripts/application.js: //= require bootstrap-sprockets
bundle
rails generate bootstrap:install --stylesheet-engine=scss
rails g scaffold student first_name last_name email
in config/routes.rb: root 'students#index'
in app/models/student.rb
validates :first_name, :last_name, presence: true
validates :email,
presence: true,
uniqueness: true
in app/models/student.rb
index({ email: 1 }, { unique: true})
rake db:mongoid:create_indexes
comment out email validation and demo
Documents are the core objects in Mongoid and any object that is to be persisted to the database must include Mongoid::Document. The representation of a Document in MongoDB is a BSON object that is very similar to a Ruby hash or JSON object. Documents can be stored in their own collections in the database, or can be embedded in other Documents n levels deep.
- Add a profile to Student, using
embeds_oneandembedded_in(Docs). Add a couple fields to the profile, and the ability to edit it in the student form. - Add Friendships to Student, using
embeds_many. A Friendship should refer to a student usinghas_one
Even though MongoDB is a schemaless database, most uses will be with web applications where form parameters always come to the server as strings. Mongoid provides an easy mechanism for transforming these strings into their appropriate types through the definition of fields in a Mongoid::Document
If you don't define a field, the following types are not supported: BigDecimal, Date, DateTime, Range
Add a phone number type to your student profile.
include Mongoid::Attributes::Dynamic
- mongoid provides dot methods, but only if attribute is set, otherwise will get a NoMethodError
- safe way to access dynamic attr is with [], []=, read_attribute, write_attribute
- Add fields to your profile without defining them in the model
- Add the ability for a user to add one custom field (name & value) to their profile
- similar to Active Record
- changed, changed?, xxxx_changed?, changes, xxxx_change, xxxx_was
include Mongoid::Timestamps
create, save similar to ActiveRecord only performs atomic updates on fields that have changed field persistence methods: inc, pop, push, unset
Mongoid Documentation Mongoid is the Ruby/Rails ODM for Mongo (replaces ActiveRecord)