In this post, we will see how we can use MongoDB with our Rails application.

MongoDB is a document oriented database and does not use SQL queries for database operations. To know more about MongoDB, click here

Let us check with an example.

  1. Download MongoDB for Windows from this link and install. Check the installation bin folder. In my case, it is:
    C:\Program Files\MongoDB\Server\3.0\bin
  2. By default, MongoDB on Windows requires the directory: c:\data\db
  3. Hence, create a folder named data on c:\ and then create folder db inside data folder.
  4. Start command prompt as administrator and move to the path: C:\Program Files\MongoDB\Server\3.0\bin
  5. Execute the following command to start the MongoDB server:
    mongod
  6. MongoDB server should be ready at this moment.;
  7. Next, create a new rails project and name it mongo:
    rails new mongo --skip-active-record

    *Note: We do not want to use the default ActiveRecord, hence we skipped it while creating the project.

  8. Edit your Gemfile, remove sqlite3 and add following line:
    gem 'mongoid', '~> 5.0.0'
  9. Execute command:
    bundle install
  10. Next to create mongodb configuration file, execute the command:
    rails generate mongoid:config

    This will create the file config/mongoid.yml. Open this file and update

    database: mongodb
  11. Now move into the project folder on command prompt.
  12. Next we will create a controller which will handle tasks for CRUD (Create, Read, Update, Delete) operations on employees. Execute the following command:
    rails g controller employees create save list edit update destroy
  13. Since we do not need views for save, update and destroy methods, go ahead and remove the following files
    app\views\employees\save.erb.html
    app\views\employees\update.erb.html
    app\views\employees\destroy.erb.html
  14. Now create a model for employee. Execute the following command:
    rails generate model Employee

    This will create a model class. The class would be located in:

    app\models\employee.rb
  15. Open the above file and make it look like this:
    class Employee
     include Mongoid::Document
    
     field :name, type: String
     field :gender, type: String
     field :email, type: String
     field :status, type: String
    end
  16. Open your command prompt and execute the following command from the project directory:
  17. So, our database is ready now. Next we will put our CRUD logic in the employee controller. Here is the code for the employee controller:
    class EmployeesController < ApplicationController
    
    def list 
       @employees = Employee.all
       @found = !@employees.empty?
    end
    
    def create
       @employee = Employee.new
    end
    
    def save
       @employee = Employee.create(employee_params)  # pass employee_params function
       if @employee.save
          redirect_to :action => 'list'
       else
          render :action => 'create'
       end
    end
    
    def destroy
       @employee = Employee.find params[:id]
       @employee.destroy
       redirect_to :action => 'list'
    end
    
    def edit
       @employee = Employee.find params[:id]
    end
    
    def update
       @employee = Employee.find params[:id]
       if @employee.update_attributes(employee_params)
          redirect_to :action => 'list'
       end
    end
    
    # this function specifies the fields to be used in mass assignment
    # older way of this was using 'attr_accessible' in model
    def employee_params
      params.require(:employee).permit(:name, :email, :gender)
    end
    
    end
  18. Next we need to update our views. Here is code for create.html.erb
    <%= link_to 'All employees', :action => 'list' %>
    <br/><br/>
    <h1>New Employee</h1>
    <%= form_for @employee, :url => {:action => 'save'} do |f| %>
     <p>
     Name: <%= f.text_field 'name' %>
     </p>
     <p>
     Email: <%= f.text_field 'email' %>
     </p>
     <p>
     Gender: <label><%= f.radio_button 'gender', "Male", :checked => true %> Male</label> &nbsp;&nbsp; <label><%= f.radio_button 'gender', "Female" %> Female</label>
     </p>
     <p>
     <%= f.submit "Create" %>
     </p>
    <% end %>
  19. Here is the code for list.html.erb
    <%= link_to 'New Employee', :action => 'create' %>
    <br/><br/>
    <% if @found %>
    <h1>Listing Employees</h1>
    <table>
     <tr>
     </tr>
    <% @employees.each do |employee| %>
     <tr>
     <td><%= employee.id %></td>
     <td><%= employee.name %></td>
     <td><%= employee.email %></td>
     <td><%= employee.gender %></td>
     <td><%= link_to 'Edit', :action => 'edit', :id => employee.id %></td>
     <td><%= link_to 'Delete', {:action => 'destroy', :id => employee.id}, :confirm => 'Are you sure to remove this employee?', :method => :post %></td>
     </tr>
    <% end %>
    </table>
    <br />
    <% else %>
     
    No employees added
     
    <% end %>
  20. Here is the code for edit.html.erb

    <h1>Edit employee</h1>
    <%= form_for @employee, :url => {:action => 'update', :id => @employee.id} do |f| %>
     <p>
     Name: <%= f.text_field 'name' %>
     </p>
     <p>
     Email: <%= f.text_field 'email' %>
     </p>
     <p>
     Gender: <label><%= f.radio_button 'gender', "Male", :checked => true %> Male</label> &nbsp;&nbsp; <label><%= f.radio_button 'gender', "Female" %> Female</label>
     </p>
     <p>
     <%= f.submit "Update" %>
     </p>
    <% end %>
  21. Finally, here are the entries in my config\routes.rb
    get 'employees/create'
    post 'employees/save'
    get 'employees/list'
    get 'employees/edit'
    post 'employees/destroy'
    patch 'employees/update'
  22. Now you can start your server and execute the url:
    http://localhost:3000/employees/list

That’s it from this post.