get in touch

LIKE

SHARE

FOLLOW

sebastian-varlan-rails-developer

Rails Developer at ASSIST

In this tutorial I will show you how to save data in a NoSQL database like Amazon DynamoDB, using Ruby on Rails framework. To make this example as useful as possible I've created the project using the following steps:

  • created a new rails application and a NoSQL database in Amazon DynamoDB
  • included the aws-sdk gem
  • created a config file with the credentials
  • implemented a method that connects to the DynamoDB table
  • created a form and processing data in POST 

I have published the entire application on ASSIST Github page. So let's get started!

Create a new Rails Application through console:

rails new app_name

Open the application generated in a IDE, search for Gemfile file and add the following gem:

gem 'aws-sdk'

Run from console:

bundle install

Create a new file named: aws_dynamo.yml in config/ folder and write the credentials:

aws_dynamo:
    access_key_id: "key_id"
    secret_access_key: "access_key"
    region: "eu-west-1"

Go to config/environment.rb and add:

AWS_SETTINGS = YAML.load_file("#{Rails.root}/config/aws_dynamo.yml")

before

Rails.application.initialize!

This is for loading the aws_dynamo.yml in a constant to be available on the entire application.

Create a new file named: aws.rb in lib/ folder and add the following code:

module Aws
 require 'time'
 #a init method to be used for initialisation when the rails application start
 def self.init
   @@dynamo_table = false
   @@dynamo_db = false
   if AWS_SETTINGS["aws_dynamo"]
     @@dynamo_db = AWS::DynamoDB.new(AWS_SETTINGS["aws_dynamo"])
   end
 end
 #the method that save in aws database
 def self.save_records_to_db(params)
   return if !@@dynamo_db
   #set the table name, hash_key and range_key from the AmazonDB
   @@dynamo_table = @@dynamo_db.tables['records']
   @@dynamo_table.hash_key = [:member_id, :number]
   @@dynamo_table.range_key = [:datetime, :string]
   fields = {
       'member_id' => 1, #primary partition key
       'datetime' => Time.now.utc.iso8601, #primary sort key
   }
   fields.merge!(params[:custom_fields]) if params[:custom_fields]
   @@dynamo_table.items.create(fields)
 end
end

Create a new file named: aws.rb in config/initializers/ and add this line to make the AWS Module available on entire application:

require 'aws'

Go back to config/environment.rb and add:

Aws.init

After

Rails.application.initialize!

Generate a new controller from command line:

rails g controller save_data index

With this command will be generated save_data_controller.rb in app/controllers/ and a save_data folder in app/views/.
Create a default route for the controller and a route to process data from POST:

root 'save_data#index'
post 'save_data/save' => 'save_data#save'

Add the html code for the form in app/views/save_data/index.erb:

<div class="container">
 <div class="row">
   <div class="col-md-4">
     <div class="form_main">
       <h4 class="heading"><strong>Quick </strong> Contact <span></span></h4>
       <div class="form">
         <%= form_tag('save', method: "post", html: {class: "contactFrn"}) do %>
           <input type="text" required="" placeholder="Please input your Name" value="" name="name" class="txt">
           <input type="text" required="" placeholder="Please input your mobile No" value="" name="mob" class="txt">
           <input type="text" required="" placeholder="Please input your Email" value="" name="email" class="txt">
           <textarea placeholder="Your Message" name="mess" type="text" class="txt_3"></textarea>
           <input type="submit" value="submit" name="submit" class="txt2">
         <% end %>
       </div>
     </div>
   </div>
 </div>
</div>

 

HTML Form to send data to the db

html-form-rails-save-data-to-amazon

For the form design I added bootstrap.css and bootstrap.js in app/views/layouts/application.html.erb. Also, I added some custom css style in app/assets/stylesheets/application.css
In app/controllers/save_data_controller.rb make sure you have this 2 methods:

 def index
 end
 def save
   name  = params['name']
   mob   = params['mob']
   email = params['email']
   mess  = params['mess']
   aws_params = Hash.new
   aws_params[:mob] = mob
   aws_params[:custom_fields]    = {
       'name'    => name,
       'email'   => email,
       'message' => mess,
   }
   if Aws.save_records_to_db(aws_params)
     flash[:notice] = "Message Sent!"
   else
     flash[:error] = "Error While Save to DynamoDB!"
   end
   redirect_to root_path
 end

Run the application from console with:

rails s

You can now access the application from:
http://localhost:3000
or
http://localhost:3000/save_data/index

 

The Amazon DynamoDB interface
dynamodb-rails-development
You can check the app on our github page https://github.com/assist-software/dynamodb-using-rails-tutorial.

If you have any question please ask below. 

Ready to make it happen?

Drop us a line. We’d love to hear from you and see how we can help in solving your digital challenges. As one of the best software outsourcing companies in Romania, Eastern Europe, Europe and the world really, we are sure we can ASSIST.

GET IN TOUCH