Ruby on Rails - Ruby on Rails CRUD - ruby on rails tutorial - rails guides - rails tutorial - ruby rails



Define CRUD ?

  • CRUD stands for Create, Read, Update, and Delete data in a database. .
  • When we talk about CRUD we mean the basic functionality needed to be able to create objects, read those objects, update the data in the objects, and delete them.
  • In Rails, CRUD has been replaced by REST as the preferred pattern, although they are similar.
  • Active Record automatically allows an application to read and manipulate data stored within tables.
learn ruby on rails - ruby on rails tutorial - ruby on rails - database access - rest api in ruby on rails - ruby on rails examples

In this rails tutorial, we will create a Rails CRUD with MySQL database.

Step 1 Create a new Rails application

rails new crud  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 2 Change your directory to crud

cd crud  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 3 Go to the Gemfile in your application and add the following.

gem 'grape'   
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 4 Go to the config/application.rb file in your application and add the following.

config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')  
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 5 Run the following command

      bundle install  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 6 Go to app/views/layouts/application.html.erb and insert the following lines in head tag.

<%= stylesheet_link_tag??? 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' %>  
<%= stylesheet_link_tag??? 'https://cdn.datatables.net/s/dt/dt-1.10.10,r-2.0.0/datatables.min.css' %>  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 7 Go to app/views/layouts/application.html.erb and insert the following lines before tag.

<%= javascript_include_tag 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js' %>  
<%= javascript_include_tag 'https://cdn.datatables.net/s/dt/dt-1.10.10,r-2.0.0/datatables.min.js' %>  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 8 In the above file, replace <%= yield %> with following code:

<div class="container">  
<div><% if flash[:notice] %>  
<div><%= flash[:notice] %></div>  
<% end %> <%= yield %></div>  
</div>  
</div>  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 9 Go to app/assets/javascripts/application.js and add the javascript code that loads jQuery DataTable:

var ready = function() {  
 $('#products').DataTable({  
  "columnDefs": [  
     { "width": "19%", className: "dt-body-center", "targets": -1 },  
     { "width": "10%", "targets": 0 },  
     { "width": "7%", "targets": 1 },  
     { "width": "20%", "targets": 2 },  
     { "width": "20%", "targets": 3 },  
    ]  
   });  
}  
$(document).ready(ready);  
$(document).on('page:load', ready);  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 10 Create a controller from the console.

rails g controller products index show new create edit update destroy
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 11 Create a model from the console

rails g model product name:string price:decimal short_description:text full_description:text  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 12 Go to app/controllers/products_controller.rb and write the following code

class ProductsController < ApplicationController   
   
  # GET method to get all products from database   
  def index   
    @products = Product.all   
  end   
   
  # GET method to get a product by id   
  def show   
    @product = Product.find(params[:id])   
  end   
   
  # GET method for the new product form   
  def new   
    @product = Product.new   
  end   
   
  # POST method for processing form data   
  def create   
    @product = Product.new(product_params)   
    if @product.save   
      flash[:notice] = 'Product added!'   
      redirect_to root_path   
    else   
      flash[:error] = 'Failed to edit product!'   
      render :new   
    end   
  end   
   
   # GET method for editing a product based on id   
  def edit   
    @product = Product.find(params[:id])   
  end   
   
  # PUT method for updating in database a product based on id   
  def update   
    @product = Product.find(params[:id])   
    if @product.update_attributes(product_params)   
      flash[:notice] = 'Product updated!'   
      redirect_to root_path   
    else   
      flash[:error] = 'Failed to edit product!'   
      render :edit   
    end   
  end   
   
  # DELETE method for deleting a product from database based on id   
  def destroy   
    @product = Product.find(params[:id])   
    if @product.delete   
      flash[:notice] = 'Product deleted!'   
      redirect_to root_path   
    else   
      flash[:error] = 'Failed to delete this product!'   
      render :destroy   
    end   
  end   
   
  # we used strong parameters for the validation of params   
  def product_params   
    params.require(:product).permit(:name, :price, :old_price, :short_description, :full_description)   
  end   
   
end  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 13 Go to app/models/product.rb and make some validations on the name, price and description fields.

class Product < ApplicationRecord   
validates :name, presence: true   
validates :price, presence: true, numericality: {:greater_than => 0}   
validates :short_description, presence: true   
end   
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 14 Go to config/routes.rb and add:

resources :products  
root 'products#index'  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 15 Now create a folder named api in app folder. Inside this folder create a folder named products. Now finally create app/api/products/products_api.rb file and add the following code.

module Products   
  class ProductsAPI < Grape::API   
   
    format :json   
   
    desc "Product List", {   
        :notes => <<-NOTE   
        Get All Products   
         __________________   
        NOTE   
    }   
   
    get do   
      Product.all   
    end   
   
   
    desc "Product By Id", {   
        :notes => <<-NOTE   
        Get Product By Id   
         __________________   
        NOTE   
    }   
   
    params do   
      requires :id, type: Integer, desc: "Product id"   
    end   
   
    get ':id' do   
      begin   
        product = Product.find(params[:id])   
      rescue ActiveRecord::RecordNotFound   
        error!({ status: :not_found }, 404)   
      end   
    end   
   
    desc "Delete Product By Id", {   
        :notes => <<-NOTE   
        Delete Product By Id   
         __________________   
        NOTE   
    }   
   
    params do   
      requires :id, type: Integer, desc: "Product id"   
    end   
   
    delete ':id' do   
      begin   
        product = Product.find(params[:id])   
        { status: :success } if product.delete   
      rescue ActiveRecord::RecordNotFound   
        error!({ status: :error, message: :not_found }, 404)   
      end   
    end   
   
    desc "Update Product By Id", {   
        :notes => <<-NOTE   
        Update Product By Id   
                        __________________   
        NOTE   
    }   
   
    params do   
      requires :id, type: Integer, desc: "Product id"   
      requires :name, type: String, desc: "Product name"   
      requires :price, type: BigDecimal, desc: "Product price"   
      optional :old_price, type: BigDecimal, desc: "Product old price"   
      requires :short_description, type: String, desc: "Product old price"   
      optional :full_description, type: String, desc: "Product old price"   
    end   
   
    put ':id' do   
      begin   
        product = Product.find(params[:id])   
        if product.update({   
                              name: params[:name],   
                              price: params[:price],   
                              old_price: params[:old_price],   
                              short_description: params[:short_description],   
                                
                          })   
          { status: :success }   
        else   
          error!({ status: :error, message: product.errors.full_messages.first }) if product.errors.any?   
        end   
   
   
      rescue ActiveRecord::RecordNotFound   
        error!({ status: :error, message: :not_found }, 404)   
      end   
    end   
   
   
    desc "Create Product", {   
        :notes => <<-NOTE   
        Create Product   
         __________________   
        NOTE   
    }   
   
    params do   
      requires :name, type: String, desc: "Product name"   
      requires :price, type: BigDecimal, desc: "Product price"   
      optional :old_price, type: BigDecimal, desc: "Product old price"   
      requires :short_description, type: String, desc: "Product old price"   
      
    end   
   
    post do   
      begin   
        product =  Product.create({   
                                      name: params[:name],   
                                      price: params[:price],   
                                      old_price: params[:old_price],   
                                      short_description: params[:short_description],   
                                        
                                  })   
        if product.save   
          { status: :success }   
        else   
          error!({ status: :error, message: product.errors.full_messages.first }) if product.errors.any?   
        end   
   
   
      rescue ActiveRecord::RecordNotFound   
        error!({ status: :error, message: :not_found }, 404)   
      end   
    end   
  end   
end  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 16 Go to config/routes.rb and add the following code

mount Products::ProductsAPI => '/api/products'  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 17 Run following command in your console.

rake db:migrate  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 18 In app/views/products/ file, write the following code

index.html.erb

<!DOCTYPE html>   
<html>   
<body>   
 <div class="container">   
    <h3>STOCK LIST</h3>   
     
      <div>   
        <%= link_to 'Add Product', new_product_path %>   
      </div>   
      <br>   
    <table border="2">   
      <thead>   
      <tr>   
        <th>Name</th>   
        <th>Price</th>   
        <th>Description</th>   
        <th>Actions</th>   
      </tr>   
      </thead>   
      <tbody>   
      <% @products.each do |product| %>   
          <tr>   
            <td><%= product.name %></td>   
            <td><%= product.price %></td>   
            <td><%= truncate(product.short_description, :length => 75) %></td>   
               <div>   
               <td>   
                <%= link_to 'Show', product_path(product) %>   
                <%= link_to 'Edit', edit_product_path(product) %>   
                <%= link_to 'Delete', product_path(product), method: :delete %>   
              </div>   
            </td>   
          </tr>   
      <% end %>   
      </tbody>   
    </table>   
    </div>   
  </body>   
</html>  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

new.html.erb

<div class="container">   
  <%= form_for @product, url: {action: :create} do |f| %>   
      <div>   
        <h3>Add a Product</h3>   
      </div>   
      <div>   
        <p>   
          <%= "<div>#{@product.errors.full_messages.first}</div>".html_safe if @product.errors.any? %>   
        <div>   
            <label>Product Name</label>   
              <%= f.text_field :name %>   
        </div>   
  
        <div>   
             <label>Price</label>   
             <%= f.text_field :price %>   
        </div>   
  
        <div>   
           <label>Description</label>   
              <%= f.text_field :short_description %>   
        </div>   
         </p>   
      </div>   
      <div>   
        <%= link_to 'Back', { controller: 'products', action: 'index'} %>   
        <%= f.submit 'Create Product' %>   
      </div>   
  <% end %>   
</div>  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

edit.html.erb

<div class="container">   
  
<%= form_for @product, url: {action: :update} do |f| %>   
     
   <h3>Add a Product</h3>   
 <%= "<div>#{@product.errors.full_messages.first}</div>".html_safe if @product.errors.any? %>   
    <p>   
  
     <div>   
            <label>Product Name</label>   
            <%= f.text_field :name %>   
     </div>   
  
     <div>   
            <label>Price</label>   
            <%= f.text_field :price %>   
     </div>   
        
     <div>   
            <label>Description</label>   
            <%= f.text_field :short_description %>   
     </div>   
  
      </p>   
   <div>   
      <%= link_to 'Back', { controller: 'products', action: 'index'} %>   
      <%= f.submit 'Update Product' %>   
    </div>   
<% end %>   
t;/div>  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

show.html.erb

<div class="container">        
        <h3>Add a Product</h3>   
      
            <div>   
              <label>Product Name</label>   
              <%= @product.name %>   
            </div>   
  
            <div>   
              <label>Price</label>   
              <%= @product.price %>   
            </div>   
            
            <div>   
              <label>Description</label>   
              <%= @product.short_description %>   
            </div>   
         
      <div>   
        <%= link_to 'Back', { controller: 'products', action: 'index'} %>   
      </div>   
</div>  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 19 Start the server from the command line.

rails s  
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team

Step 20 Run the application on your localhost.

  • localhost:3000/products
  • Following page will appear. Here we have already inserted some data in the table.
  learn ruby on rails - ruby on rails crud step1 -ruby on rails example

learn ruby on rails - ruby on rails crud step1 -ruby on rails example

ruby on rails tutorial tags - ruby , rail , ruby on rails , rail forum , ruby on rails tutorial , ruby tutorial , rails guides , rails tutorial , learn ruby

Insert Data

  learn ruby on rails - ruby on rails crud step2 -ruby on rails example

learn ruby on rails - ruby on rails crud step2 -ruby on rails example

  • To insert data, click on Add Product as shown in the above snapshot. Fill the details as shown below.
  learn ruby on rails - ruby on rails crud step3 -ruby on rails example

learn ruby on rails - ruby on rails crud step3 -ruby on rails example

Read Data

  • To read data, click on action Show. Here we will click on Jeggings Show action.
  learn ruby on rails - ruby on rails crud step4 -ruby on rails example

learn ruby on rails - ruby on rails crud step4 -ruby on rails example

  learn ruby on rails - ruby on rails crud step5 -ruby on rails example

learn ruby on rails - ruby on rails crud step5 -ruby on rails example

  learn ruby on rails - ruby on rails crud step6 -ruby on rails example

learn ruby on rails - ruby on rails crud step6 -ruby on rails example

Delete Data

  • To delete data, click on Delete action. Here we will delete product Jeans from the above table.
  learn ruby on rails - ruby on rails crud step7 -ruby on rails example

learn ruby on rails - ruby on rails crud step7 -ruby on rails example


This ruby on rails tutorial page provides you the following key areas such as ruby , rail , ruby on rails , rail forum , ruby on rails tutorial , ruby tutorial , rails guides , rails tutorial , learn ruby , rails form_for , ruby rails , ruby class , what is ruby on rails , rails installer , ruby online , learn ruby on rails , ruby on rails jobs , rails find_by , install rails , easyrail , rubyonrails , link_to rails , ruby on rails developer , learn ruby the hard way , railscasts , ruby on rails examples , ruby on rails vs php , rails 4 , rails activerecord , rails generate , ruby and rails , ruby on rails download , install ruby on rails , ruby net http , what is rails , ruby app , ruby vs ruby on rails , ruby on rails windows , rails for zombies , ruby on rails book , ruby on rails development , ruby on rails ide , ruby on rails tutorial pdf

Related Searches to Ruby on Rails CRUD